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

Tkinter中sticky属性失效求助:计算器GUI开发遇阻

Tkinter计算器Sticky属性失效问题修复
  • 核心问题:

    1. 根窗口(root)未配置行和列的权重,导致内部组件无法随窗口大小变化而拉伸。
    2. 冗余的output_frame与输入框(input_box)占据同一网格位置,造成布局冲突。
    3. 按钮设置了固定的width和height参数,限制了sticky='nsew'的拉伸效果。
  • 修复步骤:

    1. 为根窗口的行和列添加权重配置,让输入框所在行、按钮框所在行及对应列具备拉伸能力。
    2. 删除无用的output_frame代码,消除布局冲突。
    3. 移除按钮的width和height参数,让按钮通过sticky='nsew'自动填充网格单元。

修正后的代码:

import tkinter as tk

class MyCal:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Calculator")

        # 配置根窗口的行和列权重
        self.root.rowconfigure(0, weight=1)
        self.root.rowconfigure(1, weight=6)  # 按钮区域分配更大占比
        self.root.columnconfigure(0, weight=1)

        self.input_var = tk.StringVar()
        self.input_box = tk.Entry(self.root, textvariable=self.input_var, font=("Corbel", 18))
        self.input_box.grid(row=0, column=0, columnspan=4, sticky='nsew')

        self.buttonframe = tk.Frame(self.root)
        self.buttonframe.grid(row=1, column=0, sticky='nsew')

        rows = 6
        cols = 4

        # 配置按钮框的行和列权重
        for i in range(rows):
            self.buttonframe.rowconfigure(i, weight=1)
        for i in range(cols):
            self.buttonframe.columnconfigure(i, weight=1)

        button_texts = [
            "%", "CE", "C", "DEL", "1/x", "x^2", "2/x", "/", 
            "7", "8", "9", "X", "4", "5", "6", "-", 
            "1", "2", "3", "+", "+/-", "0", ".", "="
        ]

        for i in range(rows):
            for j in range(cols):
                button_text = button_texts[i * cols + j]
                # 移除固定宽高,让按钮自动拉伸
                button = tk.Button(self.buttonframe, text=button_text, font=("Corbel", 18))
                button.grid(row=i, column=j, sticky='nsew', padx=1, pady=1)

        self.root.mainloop()

MyCal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:46:12