You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter如何实现渐变Frame随窗口大小动态调整尺寸

实现Tkinter渐变Frame随窗口自适应尺寸的方案

你当前的代码硬编码了窗口初始尺寸和每个渐变Frame的宽高、位置参数,无法响应窗口大小变化。我们通过绑定窗口的<Configure>事件,在每次窗口尺寸变更时动态重新计算每个渐变Frame的宽度和摆放位置,即可实现自适应效果。

修改后的完整可运行代码如下:

from tkinter import *

class InventorySystem:
    def __init__(self, root):
        self.root = root
        self.root.title("Inventory System")
        self.root.geometry("1366x768")
        
        # 渐变颜色列表
        self.colors = ["#007F5F", "#2B9348", "#55A630", "#80B918", "#AACC00", "#BFD200",
                  "#D4D700", "#DDDF00", "#EEEF20", "#FFFF3F"]
        # 存储所有渐变Frame实例
        self.gradient_frames = []
        # 初始化创建Frame
        for color in self.colors:
            frame = Frame(self.root, bg=color)
            frame.place(x=0, y=0)
            self.gradient_frames.append(frame)
        
        # 绑定窗口大小变化事件
        self.root.bind("<Configure>", self.update_gradient_size)
    
    def update_gradient_size(self, event):
        # 获取当前窗口的实际宽高
        win_width = self.root.winfo_width()
        win_height = self.root.winfo_height()
        # 计算每个渐变条的宽度
        per_width = win_width / len(self.colors)
        
        current_x = 0
        for frame in self.gradient_frames:
            # 重新设置Frame的尺寸和位置
            frame.place_configure(x=current_x, y=0, width=per_width, height=win_height)
            current_x += per_width

if __name__ == "__main__":
    root = Tk()
    application = InventorySystem(root)
    root.mainloop()

核心改动说明:

  • 新增实例属性self.gradient_frames存储所有渐变Frame的引用,避免每次窗口变化都重新创建组件
  • 新增update_gradient_size方法,专门处理窗口尺寸变化后的渐变条重绘逻辑,通过winfo_width()和winfo_height()动态获取当前窗口的实际尺寸
  • 绑定根窗口的<Configure>事件,只要窗口大小发生变化就自动触发重绘逻辑,无需手动操作

内容的提问来源于stack exchange,提问作者JackFrost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:48:03