I need to know when the Canvas is resized (eg when the master frame gets maximized) the new Canvas window size. Unfortunately, if I try self.canvas['width'] it always seems to me I get back the width it had whenever I initialized it and not the current width. How do I get the current Canvas window dimensions?
When you retrieve self.canvas['width']
, you are asking tkinter to give you the configured width of the widget, not the actual width. For the actual width you can use .winfo_width()
.
If you want to know when the canvas is resized, you can add a binding to the <Configure>
event on the widget. The event object that is passed to the binding has a width
attribute which also has the actual width of the widget.
Here's an example:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=200, height=200, background="bisque")
canvas.pack(side="bottom", fill="both", expand=True)
canvas.create_text(10, 30, anchor="sw", tags=["event"])
canvas.create_text(10, 30, anchor="nw", tags=["cget"])
def show_width(event):
canvas.itemconfigure("event", text="event.width: %s" % event.width)
canvas.itemconfigure("cget", text="winfo_width: %s" % event.widget.winfo_width())
canvas.bind("<Configure>", show_width)
root.mainloop()
one possible solution:
try:
import Tkinter as tk
except:
import tkinter as tk
class myCanvas(tk.Frame):
def __init__(self, root):
#self.root = root
self.w = 600
self.h = 400
self.canvas = tk.Canvas(root, width=self.w, height=self.h)
self.canvas.pack( fill=tk.BOTH, expand=tk.YES)
root.bind('<Configure>', self.resize)
def resize(self, event):
self.w = event.width
self.h = event.height
print ('width = {}, height = {}'.format(self.w, self.h))
root = tk.Tk()
root.title('myCanvas')
myCanvas(root)
root.mainloop()
Notice that the size informed by the event is 2 pixels wider in either direction. That's the border, I suppose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With