【发布时间】:2014-05-15 07:38:28
【问题描述】:
所以在回答这个question 的过程中,我遇到了 Tkinter 的一些奇怪行为。我有一个类可以调整 Canvas 实例的大小以及在其上绘制的任何小部件。但是,当我运行代码时,无论初始窗口尺寸如何,窗口都会不断扩展,直到它填满整个屏幕。发生这种情况后,窗口的行为完全符合预期,正确调整对象的大小。窗口只会在启动时展开以填满屏幕。
通过阅读 Tkinter 文档,我可以相信这可能是特定于平台的(虽然我没有任何证据)。
我的问题是:为什么会这样?我怎样才能阻止它?
代码如下:
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()
【问题讨论】:
-
画布在
highlightthickness选项中添加了四个额外的像素,因此 event.width/height 正在尝试调整大小以赶上。见:stackoverflow.com/questions/11974710/… -
你应该把它作为答案,因为它解决了设置
highlightthickness=0的问题。我仍然不完全清楚为什么会发生这种情况,因为我假设config只会被调用一次来设置这个参数,这会导致一次调整大小。
标签: python user-interface callback tkinter