如何让Tkinter窗口背景(Canvas)也可调整大小?
解决Tkinter Canvas随窗口缩放的问题
首先纠正你代码里的一个错误:设置窗口可调整大小的正确写法是window.resizable(True, True),直接给resizeable属性赋值的方式是无效的。
要让Canvas随窗口一同缩放,只需在pack()方法中添加两个关键参数:
fill=BOTH:让Canvas在水平和垂直方向上填满父容器expand=True:允许Canvas在窗口尺寸变化时自动扩展空间
修正后的基础功能代码如下:
from tkinter import * window = Tk() window.resizable(True, True) # 修正窗口可调整的方法调用 Background_Color = '#000000' canvas = Canvas(window, bg=Background_Color) canvas.pack(fill=BOTH, expand=True) # 添加fill和expand参数实现缩放 window.mainloop()
如果你的Canvas上绘制了自定义图形,需要让这些图形也跟着窗口缩放的话,可以绑定窗口的<Configure>事件,在窗口尺寸变化时重新计算图形尺寸并刷新。示例代码如下:
from tkinter import * def resize_canvas(event): # 获取窗口新尺寸 new_width = event.width new_height = event.height # 调整Canvas尺寸 canvas.config(width=new_width, height=new_height) # 清除旧图形并重新绘制(以矩形背景为例) canvas.delete("all") canvas.create_rectangle(0, 0, new_width, new_height, fill=Background_Color) window = Tk() window.resizable(True, True) Background_Color = '#000000' canvas = Canvas(window, bg=Background_Color) canvas.pack(fill=BOTH, expand=True) # 绑定窗口大小变化事件 canvas.bind("<Configure>", resize_canvas) window.mainloop()
内容的提问来源于stack exchange,提问作者Dragonite
相关产品推荐
相关产品推荐

