gpt4 book ai didi

python - 如何让 tkinter Canvas 动态调整为窗口宽度?

转载 作者:IT老高 更新时间:2023-10-28 22:08:24 71 4
gpt4 key购买 nike

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

有没有办法(轻松)做到这一点?

最佳答案

我想我会添加一些额外的代码来扩展 @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()

关于python - 如何让 tkinter Canvas 动态调整为窗口宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22835289/

71 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com