Python Tkinter报错:name 'buttonOnOff'未定义,按钮切换功能失效
解决Tkinter按钮切换状态时的NameError问题
问题描述
我尝试实现点击按钮切换开关状态的功能,但一直触发NameError。试过调整函数和按钮的创建顺序:把按钮放函数前面的话,函数又调用不了。
原代码
#import all of tkinter and also updated widgets from tkinter import * from tkinter import ttk import main #sets up main application window root = Tk() root.title("Winstreak Counter GUI") #creating a content frame (frame widget, hold content of user interface) #we do this because it'll allow us to control the background color and allow for more themed widgets mainframe = ttk.Frame(root, padding="3 3 12 12") mainframe.grid(column=10, row=10, sticky=(N, W, E, S)) root.columnconfigure(10, weight=1) root.rowconfigure(10, weight=1) f = open('/Users/ripkoye/Desktop/WinstreakProject/winstreak.txt', 'r') #store the information into a variable winstreak = StringVar(mainframe) winstreak.set(f.read()) #creates a winstreaklabel winstreaklabel = ttk.Label(mainframe,width=20, padding='5 5 5 5') winstreaklabel.grid() winstreaklabel['textvariable'] = winstreak #assigns the text to the variable named winstreak f.close() is_on = True def switch(): global is_on if is_on: buttonOnOff.config(image = off) is_on = False else: buttonOnOff.config(image = on) is_on = True on = PhotoImage(file='on.png') off = PhotoImage(file='off.png') buttonOnOff = ttk.Button(mainframe, image=on, width=0.5, padding='5 5 5 5', command=switch()) buttonOnOff.grid() root.mainloop()
报错信息
Traceback (most recent call last): File "/Users/ripkoye/Desktop/WinstreakProject/gui.py", line 42, in <module> buttonOnOff = ttk.Button(mainframe, image=on, width=0.5, padding='5 5 5 5', command=switch()) File "/Users/ripkoye/Desktop/WinstreakProject/gui.py", line 34, in switch buttonOnOff.config(image = off) NameError: name 'buttonOnOff' is not defined
解决步骤
修正按钮command参数:
创建按钮时command=switch()会立即执行switch函数,而非点击按钮时触发。需改成command=switch(去掉括号),这样才会把函数对象绑定到按钮点击事件上。让函数能访问buttonOnOff变量:
在switch函数里,除声明global is_on外,还要加上global buttonOnOff,确保函数能识别这个全局变量。
修改后的代码
from tkinter import * from tkinter import ttk import main root = Tk() root.title("Winstreak Counter GUI") mainframe = ttk.Frame(root, padding="3 3 12 12") mainframe.grid(column=10, row=10, sticky=(N, W, E, S)) root.columnconfigure(10, weight=1) root.rowconfigure(10, weight=1) f = open('/Users/ripkoye/Desktop/WinstreakProject/winstreak.txt', 'r') winstreak = StringVar(mainframe) winstreak.set(f.read()) winstreaklabel = ttk.Label(mainframe,width=20, padding='5 5 5 5') winstreaklabel.grid() winstreaklabel['textvariable'] = winstreak f.close() is_on = True def switch(): global is_on, buttonOnOff # 新增buttonOnOff的全局声明 if is_on: buttonOnOff.config(image = off) is_on = False else: buttonOnOff.config(image = on) is_on = True on = PhotoImage(file='on.png') off = PhotoImage(file='off.png') # 去掉switch后面的括号 buttonOnOff = ttk.Button(mainframe, image=on, width=0.5, padding='5 5 5 5', command=switch) buttonOnOff.grid() root.mainloop()
内容的提问来源于stack exchange,提问作者Ryan Dang
相关产品推荐
相关产品推荐

