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

Tkinter按钮点击时获取文本框值并更新标签的问题

解决Tkinter按钮函数中无法访问控件的问题

你的问题出在两个核心点:

  • 创建的文本框PoleMaticen和标签GLabel_250是__init__方法内的局部变量,类的其他方法(比如按钮点击函数)无法直接访问
  • 错误使用了Text控件的取值语法get("1.0", "end")来获取Entry控件的值,Entry控件只需调用get()方法即可

修复步骤:

  • 在创建控件时,给变量添加self.前缀,将它们转为类的实例属性,这样整个类的方法都能访问到这些控件
  • 修正Entry控件的取值代码,改为self.PoleMaticen.get()
  • 更新标签文本时,通过self.GLabel_250来访问标签控件

修改后的完整代码:

import tkinter as tk
from tkinter import font as tkFont
import openpyxl

class App:
    def __init__(self, root):
        # 设置窗口标题
        root.title("Some title")
        # 设置窗口大小与位置
        width=272
        height=297
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        # 转为实例属性,方便类内方法访问
        self.PoleMaticen=tk.Entry(root)
        self.PoleMaticen["borderwidth"] = "1px"
        ft = tkFont.Font(family='Arial',size=10)
        self.PoleMaticen["font"] = ft
        self.PoleMaticen["fg"] = "#333333"
        self.PoleMaticen["justify"] = "left"
        self.PoleMaticen.insert(0, "INPUT THE NUMBER")  # Entry用insert设置初始文本更规范
        self.PoleMaticen.place(x=110,y=10,width=139,height=30)
        self.PoleMaticen.focus()

        # 转为实例属性
        self.GLabel_250=tk.Label(root)
        self.GLabel_250["anchor"] = "ne"
        ft = tkFont.Font(family='Arial',size=10)
        self.GLabel_250["font"] = ft
        self.GLabel_250["fg"] = "#333333"
        self.GLabel_250["justify"] = "left"
        self.GLabel_250["text"] = "The number"
        self.GLabel_250.place(x=10,y=10,width=87,height=30)
        
        GButton_baraj=tk.Button(root)
        GButton_baraj["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Arial',size=10)
        GButton_baraj["font"] = ft
        GButton_baraj["fg"] = "#000000"
        GButton_baraj["justify"] = "center"
        GButton_baraj["text"] = "Lookup"
        GButton_baraj.place(x=20,y=90,width=227,height=30)
        GButton_baraj["command"] = self.GButton_baraj_command

    def GButton_baraj_command(self):
        wb = openpyxl.load_workbook("workbook.xlsx")
        ws = wb.active
        # 正确获取Entry的值
        number = self.PoleMaticen.get()
        # 更新标签文本
        self.GLabel_250["text"] = number
         

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 23:57:27