Tkinter更新Label文本报错:'_tkinter.tkapp'无balance_label属性
解决Tkinter分文件结构下Label文本更新失败的问题
问题描述
执行self.balance_label['text'] = "Text updated"时触发错误:AttributeError: '_tkinter.tkapp' object has no attribute 'balance_label'
采用分文件结构:
- file1(trade_helper.py):GUI代码
- file2(trade_helper_support.py):主逻辑代码
settext函数在类内部运行正常,需要实现按钮点击跨文件更新Label文本的功能。
原file1(trade_helper.py)代码
import sys import tkinter as tk import tkinter.ttk as ttk from tkinter.constants import * import os.path _script = sys.argv[0] _location = os.path.dirname(_script) import trade_helper_support _bgcolor = '#d9d9d9' # X11 color: 'gray85' _fgcolor = '#000000' # X11 color: 'black' _compcolor = 'gray40' # X11 color: #666666 _ana1color = '#c3c3c3' # Closest X11 color: 'gray76' _ana2color = 'beige' # X11 color: #f5f5dc _tabfg1 = 'black' _tabfg2 = 'black' _tabbg1 = 'grey75' _tabbg2 = 'grey89' _bgmode = 'light' class root: def __init__(self, top=None): '''This class configures and populates the toplevel window. top is the toplevel containing window.''' top.geometry("600x450+468+138") top.minsize(120, 1) top.maxsize(3844, 1061) top.resizable(1, 1) top.title("Trade Helper v1.0") top.configure(background="#d9d9d9") self.top = top self.menubar = tk.Menu(top,font="TkMenuFont",bg=_bgcolor,fg=_fgcolor) top.configure(menu = self.menubar) self.Get_balance_button = tk.Button(self.top) self.Get_balance_button.place(relx=0.283, rely=0.689, height=44 , width=127) self.Get_balance_button.configure(activebackground="beige") self.Get_balance_button.configure(activeforeground="black") self.Get_balance_button.configure(background="#e35e8c") self.Get_balance_button.configure(command=trade_helper_support.get_balance) self.Get_balance_button.configure(compound='left') self.Get_balance_button.configure(disabledforeground="#a3a3a3") self.Get_balance_button.configure(foreground="#000000") self.Get_balance_button.configure(highlightbackground="#d9d9d9") self.Get_balance_button.configure(highlightcolor="black") self.Get_balance_button.configure(pady="0") self.Get_balance_button.configure(text='''get balance''') self.balance_label = tk.Label(self.top) self.balance_label.place(relx=0.1, rely=0.711, height=31, width=74) self.balance_label.configure(anchor='w') self.balance_label.configure(background="#ffffff") self.balance_label.configure(compound='left') self.balance_label.configure(disabledforeground="#a3a3a3") self.balance_label.configure(foreground="#000000") self.balance_label.configure(text='''Balance''') def settext(self): print('here') self.balance_label['text'] = "Text updated" def start_up(): trade_helper_support.main() if __name__ == '__main__': trade_helper_support.main()
原file2(trade_helper_support.py)代码
import sys import tkinter as tk import tkinter.ttk as ttk from tkinter.constants import * import trade_helper def main(*args): '''Main entry point for the application.''' global root root = tk.Tk() root.protocol( 'WM_DELETE_WINDOW' , root.destroy) # Creates a toplevel widget. global _top1, _w1 _top1 = root _w1 = trade_helper.root(_top1) root.mainloop() def get_balance(*args): print('trade_helper_support.get_balance') trade_helper.root.settext(root) for arg in args: print (' another arg:', arg) sys.stdout.flush() if __name__ == '__main__': trade_helper.start_up()
错误原因
在get_balance函数中,trade_helper.root.settext(root)的调用逻辑错误:
root是Tk窗口实例,不是trade_helper.root类的实例settext是实例方法,必须通过trade_helper.root类的实例对象调用,而非直接调用类方法或传入Tk窗口对象
修正方案
方案一:使用全局保存的GUI实例
file2中已经全局定义了_w1(trade_helper.root的实例),直接调用其settext方法:
def get_balance(*args): print('trade_helper_support.get_balance') # 调用全局的GUI实例方法 _w1.settext() for arg in args: print (' another arg:', arg) sys.stdout.flush()
方案二:传递GUI实例到回调函数(推荐)
- 修改file1中按钮的
command绑定,传递当前GUI实例:
# 在root类的__init__方法内修改按钮配置 self.Get_balance_button.configure(command=lambda: trade_helper_support.get_balance(self))
- 修改file2的
get_balance函数,接收实例并调用方法:
def get_balance(gui_instance, *args): print('trade_helper_support.get_balance') gui_instance.settext() for arg in args: print (' another arg:', arg) sys.stdout.flush()
方案二更符合面向对象设计,避免依赖全局变量,代码耦合度更低。
内容的提问来源于stack exchange,提问作者Marc Robitaille
相关产品推荐
相关产品推荐

