如何让 tkinter 画布动态调整至窗口宽度?
- 2025-03-21 09:07:00
- admin 原创
- 39
问题描述:
我需要在 tkinter 中获取一个画布,将其宽度设置为窗口的宽度,然后当用户将窗口变小/变大时动态地调整画布的大小。
有什么方法可以(轻松地)做到这一点吗?
解决方案 1:
我想我会添加一些额外的代码来扩展@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()
解决方案 2:
您可以使用.pack
几何管理器:
self.c=Canvas(…)
self.c.pack(fill="both", expand=True)
应该可以解决问题。如果您的画布位于框架内,请对框架执行相同操作:
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)
查看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)
再次查看effbot以了解事件和绑定
解决方案 3:
这样做确实可行 - 至少在我的 Python 版本中如此。画布可水平(sticky=E+W 和 rowconfigure)和垂直(sticky=N+S 和 columnconfigure)调整大小。我已将画布背景设置为令人厌恶的颜色 - 但至少您可以看到它何时起作用。
from tkinter import *
root=Tk()
root.rowconfigure(0,weight=1)
root.columnconfigure(0,weight=1)
canv=Canvas(root, width=600, height=400, bg='#f0f0c0')
canv.grid(row=0, column=0, sticky=N+S+E+W)
root.mainloop()
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD