tkinter Canvas window size

五迷三道 提交于 2019-12-12 16:02:56

问题


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?


回答1:


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()



回答2:


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.



来源:https://stackoverflow.com/questions/40780634/tkinter-canvas-window-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!