Вопрос

I am creating a tkinter canvas, and I need to check for when the user changes the size of the window. The problem is, initially the window apparently isn't the size it's supposed to be. I have the following:

def print_size(self):
    print self.root.winfo_width()

def init_simulation(self, size=300):
    self.root = Tk()
    canvas = Canvas(self.root, width=size, height=size)
    self.print_size()
    self.root.after(1000, self.print_size)

When running this I get:

1

and a second later:

306

Ignoring the fact that tkinter will add 6 pixels, why is the size first 1 and then 306? Am I setting it up wrong?

Это было полезно?

Решение

When you instantiate a root widget with Tk(), Tkinter starts a process in a separate thread to actually create the window - it doesn't happen in the main loop.

The reason you get a 1 for the size initially is that the root window doesn't exist yet when you call self.print_size the first time, so it gives you a default value of 1. The next time you call it a second later, the window has finished spawning, so it gives the the actual size. It's essentially a race condition - the main event loop gets to the print self.root.winfo_width() before self.root is done being created.

If you'd like to change this behavior, add this line right after self.root = Tk():

self.root.wait_visibility(self.root)

That command forces the main event loop to pause until the given widget (in this case the root window) has been spawned and is visible.

Also, note that you've set the size of the canvas to 300 pixels, so naturally the container window will have some extra width.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top