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
相关产品推荐
相关产品推荐

