在回答这个问题的过程中,我遇到了一些有关Tkinter的奇怪行为。我有一个类,可以调整
从阅读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 尝试调整大小以跟上。请参见:https://dev59.com/GmfWa4cB1Zd3GeqPf1Ex - atlasologisthighlightthickness=0
的问题。然而,我仍然不完全清楚为什么会发生这种情况,因为我认为config
只会被调用一次来设置此参数,并且这将导致单个调整大小。 - ebarr