+ 1
How to set a canvas into the main window?
I was trying to put a Canvas into the main window. But although the master is the main window and I pack it like every other widget, it doesn't work as expected: A second Tk opens, which is the Canvas, separate from the root. Why does this happen and is it somehow possible to do what I want instead?
16 RĂ©ponses
+ 1
HonFu Iâm pretty sure that canvas should work like every other widget so it shouldnât open a new window. Copy this code and run it:
from tkinter import *
master = Tk()
canvas_width = 80
canvas_height = 40
w = Canvas(master,
width=canvas_width,
height=canvas_height)
w.pack()
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y, fill="#476042")
mainloop()
What happens when you run it?
+ 1
I'm just starting out with tkinter.
My understanding was that there is a 'mommy', that Tk-object, and that every widget declaring her master will be part of that mommy window.
And that is true for Lable, Button, RadioButton, Entry, Checkbutton, Frame, Scale...
Only Canvas is being a spoilsport starting a thing of her own.
+ 1
HonFu (Incase youâre still having problems with the program) I just ran your code on my pc and it worked like I expected. So it opened a new window and packed the canvas on there and it didnât open any new windows.
+ 1
Hm, interesting...
I am not close to my PC right now, but I will copypaste this into there later and report.
+ 1
HonFu No problem :)
0
Can you share your code, please?
0
I appreciate the spirit of letting people show code; in this case I'll just be spelling out what I already wrote though.
from tkinter import *
m = Tk()
c = Canvas(master=m)
c.pack()
m.mainloop()
What I expect: A canvas as one element of the main window.
What I get: Two separate windows.
Any way around this?
0
HonFu Maybe the m in m.mainloop() calls Tk() again and it opens a new window
0
Goodester, have you worked with tkinter?
0
HonFu Yep, a little bit.
0
HonFu I donât see anything wrong with your code though and I canât really debug it right now because I canât use my pc.
0
Have you used Canvas yourself?
0
HonFu Yes like a year ago I donât use it very often
0
HonFu Have you tried to pack some other widget instead of Canvas on the master so you could see if Canvas is causing the bug?
0
It works perfectly fine with everything else.
0
Goodester, I just tried your example...
... and it worked. oO
Now I am relieved that everything is as it should be, but the question, what the heck I was doing differently, will be haunting me for a while...
Anyway, thanks a lot for your help! :)