如何获得tkintercanvasdynamic调整窗口宽度?

我需要在tkinter中获取一个canvas,将其宽度设置为窗口的宽度,然后在用户使窗口变小/变大时dynamic地重新调整canvas的大小。

有没有办法做到这一点(容易)?

我想我会添加一些额外的代码来扩展@ fredtantini的答案,因为它不涉及如何更新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几何pipe理器:

 self.c=Canvas(…) self.c.pack(fill=BOTH, expand=YES) 

应该做的伎俩。 如果您的canvas在一个框架内,请对框架执行相同的操作:

 self.r = root self.f = Frame(self.r) self.f.pack(fill=BOTH, expand=YES) self.c = Canvas(…) self.c.pack(fill=BOTH, expand=YES) 

有关更多信息,请参阅effbot 。

编辑:如果你不想要一个“全尺寸”的canvas,你可以绑定你的canvas到一个函数:

 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) 

请再次查看事件和绑定