2

There was a previous question asked, here, regarding getting the dimensions of a widget, whenever the window's size is changed.

The linked question and answer work perfectly, but I have a follow up question, and sadly because my account is quite new, I'm not allowed to post comments yet!

My question is; what is the effective difference between:

event.width

and

event.widget.winfo_width()

My full code is below.

from tkinter import *

root = Tk()

display = Canvas(root, width=300, height=300, background="bisque")
display.pack(fill="both", expand=True)

display.create_text(10, 15, anchor="w", tags=["events"])
display.create_text(10, 30, anchor="w", tags=["winfos"])


def show_dims(event):
    display.itemconfigure("events", text="event.width: {0}, event.height: {1}".format(event.width, event.height))
    display.itemconfigure("winfos", text="winfo_width: {0}, winfo_height: {1}".format(event.widget.winfo_width(), event.widget.winfo_height()))

display.bind("<Configure>", show_dims)

root.mainloop()

As far as I can tell, the code works perfectly. As the window size is changed, the "< Configure>" event calls the show_dims function, which updates the displayed text to show the current width and height of the window in pixels.

Are the two ways I've used of getting window dimensions the same? Is one better for some reason?

Thanks,

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685

1 Answers1

2

Looking at the event documentation:

width - width of the exposed window (Configure, Expose)

So in your particular case, event.width and event.widget.winfo_width() are exactly the same always.

But with a different event:

from tkinter import *

root = Tk()
d = Label(root, width=50, height=50, text="HI")
d.pack(expand=True)

def check(event):
    print(event.width)
    print(event.widget.winfo_width())

d.bind("<1>", check)
root.mainloop()

This code displays:

??
456

So the winfo methods must be used unless the event is Configure or Expose. event.width is probably more readable to a client.

rassar
  • 5,412
  • 3
  • 25
  • 41
  • Hi Rassar, thanks so much for replying. So if I understand you correctly: If the event being bound is `Configure` or `Expose` ONLY, then either can be used (but `event.width` is more readable) If the event is ANYTHING ELSE, then `winfo` must be used. I must say, it seems a little redundant to have a method that can only be used in certain cases, which doesn't offer anything different to the alternative, universally usable method. I will read the documentation further to try to understand this. Thanks so much again, Will – William Pulford Dec 29 '17 at 17:07
  • 1
    @WilliamPulford: _" it seems a little redundant to have a method that can only be used in certain cases"_ - `event.width` isn't a method, it's an attribute on an object. – Bryan Oakley Dec 31 '17 at 15:09