Python Forum
Tkinter: puzzlement with creating a canvas widget
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tkinter: puzzlement with creating a canvas widget
#1
I have successfully created a widget of type Canvas, but when I want to use its attributes I get a NoneType error
root = tk.Tk()
frame = tk.Frame(root)
frame.grid()
panel = tk.Canvas(frame, width=panel_width, height=panel_height, bg="silver").grid(row=0, column=0)
btn = tk.Button(frame, text="Quit", command=root.destroy).grid(row=1, column=0)

The canvas is created, but the name is not recognized in the next statement:
panel.create_line(0, 20, panel_width, 20, fill="red", width=2)
I get an error:
AttributeError: 'NoneType' object has no attribute 'create_line'

I must be doing something wrong... Thanks in advance for any help
Reply
#2
.grid() returns None. When you call x = Widget(params).grid(row=0, column=0), x == None.

Python is not designed to daisy chain method calls. The accepted pattern is:
x = Widget(params)
x.grid()
Like you did with frame.

You should be debugging this kind of problem yourself. Better for learning and a lot faster.

The error says panelis None, so lets check the value of panel.
root = tk.Tk()
frame = tk.Frame(root)
frame.grid()
panel = tk.Canvas(frame, width=panel_width, height=panel_height, bg="silver").grid(row=0, column=0)
print(panel)
btn = tk.Button(frame, text="Quit", command=root.destroy).grid(row=1, column=0)
Output:
None
Not much code between creating panel and printing panel, so break up the code so it runs a line at a time.
root = tk.Tk()
frame = tk.Frame(root)
frame.grid()
panel = tk.Canvas(frame, width=panel_width, height=panel_height, bg="silver")
print(panel)
panel.grid(row=0, column=0)
print(panel)
btn = tk.Button(frame, text="Quit", command=root.destroy).grid(row=1, column=0)
Output:
.!frame.!canvas .!frame.!canvas
Now the code runs.

In this code btn is also None:
btn = tk.Button(frame, text="Quit", command=root.destroy).grid(row=1, column=0)
It's likely you don't need a handle to btn, so you can write like this.
tk.Button(frame, text="Quit", command=root.destroy).grid(row=1, column=0)
Reply
#3
Thanks.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  tkinter only storing last element/data from entry widget bertschj1 8 1,969 May-06-2025, 11:54 PM
Last Post: deanhystad
  Any way to speed up canvas itemconfigure (tkinter) Klapek123 0 805 Jan-19-2025, 05:04 PM
Last Post: Klapek123
  Tkinter & Canvas Peter_Emp1 5 3,713 Mar-24-2024, 07:40 PM
Last Post: deanhystad
  how to positon a tkinter canvas Tyrel 3 3,495 Dec-11-2020, 03:05 PM
Last Post: deanhystad
  use classes in tkinter canvas fardin 2 4,446 Jan-06-2019, 04:23 AM
Last Post: fardin

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020