Ann*_*ous 32 python canvas tkinter autoresize python-3.x
我需要在tkinter中获取一个画布,将其宽度设置为窗口的宽度,然后在用户使窗口变小/变大时动态地重新调整画布大小.
有没有办法(轻松)这样做?
eba*_*arr 31
我想我会添加一些额外的代码来扩展@ 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()
Run Code Online (Sandbox Code Playgroud)
fre*_*ini 13
您可以使用.pack几何管理器:
self.c=Canvas(…)
self.c.pack(fill="both", expand=True)
Run Code Online (Sandbox Code Playgroud)
应该做的伎俩.如果画布位于框架内,请对框架执行相同操作:
self.r = root
self.f = Frame(self.r)
self.f.pack(fill="both", expand=True)
self.c = Canvas(…)
self.c.pack(fill="both", expand=True)
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅effbot.
编辑:如果您不想要"全尺寸"画布,可以将画布绑定到一个函数:
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)
Run Code Online (Sandbox Code Playgroud)
再次看到effbot的事件和绑定
| 归档时间: |
|
| 查看次数: |
70476 次 |
| 最近记录: |