回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>所以在回答这个问题的过程中,我遇到了来自Tkinter的一些奇怪的行为。我有一个类,它可以调整一个<code>Canvas</code>实例的大小,以及在该实例上绘制的任何小部件的大小。但是,当我运行代码时,不管窗口的初始尺寸是多少,窗口都会不断地扩展,直到填满整个屏幕。发生这种情况后,窗口的行为与预期完全一样,可以正确调整对象的大小。窗口仅在启动时展开以填充屏幕。</p>
<p>通过阅读Tkinter文档,我可以相信这可能是特定于平台的(但我没有任何证据)。</p>
<p>我的问题是:为什么会这样?我怎样才能阻止它?</p>
<p>代码如下:</p>
<pre><code>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")
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()
</code></pre>