如何让tkinter画布动态调整窗口宽度?

2024-04-20 10:04:56 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
2条回答

我想我应该添加一些额外的代码来扩展@fredtantini's answer,因为它不涉及如何更新在Canvas上绘制的小部件的形状。

为此,您需要使用scale方法并标记所有小部件。下面是一个完整的例子。

from Tkinter import *

# a subclass of Canvas for dealing with resizing of windows
class ResizingCanvas(Canvas):
    def __init__(self,parent,**kwargs):
        Canvas.__init__(self,parent,**kwargs)
        self.bind("<Configure>", self.on_resize)
        self.height = self.winfo_reqheight()
        self.width = self.winfo_reqwidth()

    def on_resize(self,event):
        # determine the ratio of old width/height to new width/height
        wscale = float(event.width)/self.width
        hscale = float(event.height)/self.height
        self.width = event.width
        self.height = event.height
        # resize the canvas 
        self.config(width=self.width, height=self.height)
        # rescale all the objects tagged with the "all" tag
        self.scale("all",0,0,wscale,hscale)

def main():
    root = Tk()
    myframe = Frame(root)
    myframe.pack(fill=BOTH, expand=YES)
    mycanvas = ResizingCanvas(myframe,width=850, height=400, bg="red", highlightthickness=0)
    mycanvas.pack(fill=BOTH, expand=YES)

    # add some widgets to the canvas
    mycanvas.create_line(0, 0, 200, 100)
    mycanvas.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))
    mycanvas.create_rectangle(50, 25, 150, 75, fill="blue")

    # tag all of the drawn widgets
    mycanvas.addtag_all("all")
    root.mainloop()

if __name__ == "__main__":
    main()

可以使用.pack几何图形管理器:

self.c=Canvas(…)
self.c.pack(fill="both", expand=True)

应该会成功的。 如果画布位于框架内,请对框架执行相同操作:

self.r = root
self.f = Frame(self.r)
self.f.pack(fill="both", expand=True)
self.c = Canvas(…)
self.c.pack(fill="both", expand=True)

有关详细信息,请参见effbot

编辑:如果不需要“全尺寸”画布,可以将画布绑定到函数:

self.c.bind('<Configure>', self.resize)

def resize(self, event):
    w,h = event.width-100, event.height-100
    self.c.config(width=w, height=h)

有关事件和绑定,请再次参见effbot

相关问题 更多 >