[英]Python 3.4.1, Tkinter 8.6.3, Event within class throwing 'Name not defined' error when looking for class button
我试图在用户单击另一个按钮后将按钮的状态设置为“正常”,但是由于某种原因,该事件似乎无法找到我要引用的按钮,并引发了NameError: name 'rawButton' is not defined'
错误。 我试过在按钮前加上self.
但是然后我得到一个self not defined
错误。 我已经四处张望,一辈子都无法弄清楚为什么这行不通...预先感谢您提供的任何帮助。
相关代码如下:
import tkinter as tk
from imaging import *
class MainClass:
root = tk.Tk()
root.title('Main Window')
def call_bgFrame(self):
self.background = bgFrame()
rawButton.config(state = 'normal')
labels = ['Calibration','Background','Raw Data','Bin','Plot']
calibButton = tk.Button(root,text = labels[0], width = 20, height = 5)
bgButton = tk.Button(root,text = labels[1], width = 20, height = 5)
rawButton = tk.Button(root,text = labels[2], width = 20, height = 5, state = 'disabled')
binButton = tk.Button(root,text = labels[3], width = 20, height = 5, state = 'disabled')
plotButton = tk.Button(text = labels[3], width = 40, height = 5, state = 'disabled')
calibButton.grid(row = 0, column = 0)
bgButton.grid(row=0,column=1)
rawButton.grid(row=0,column=2)
binButton.grid(row=1,column=0)
plotButton.grid(row=1,column=1,columnspan = 2)
bgButton.bind('<Button-1>', call_bgFrame)
tk.mainloop()
注意: bgFrame()
函数是从映像导入的函数之一,用于返回数组(使用numpy)。
您的编码风格非常混乱。 可以通过坚持一种更通用的编码样式来解决该问题:将代码移到__init__
,并将对小部件的引用保存为实例变量。
import Tkinter as tk
from imaging import *
class MainClass:
def __init__(self):
root = tk.Tk()
root.title('Main Window')
labels = ['Calibration','Background','Raw Data','Bin','Plot']
self.calibButton = tk.Button(root,text = labels[0], width = 20, height = 5)
self.bgButton = tk.Button(root,text = labels[1], width = 20, height = 5)
self.rawButton = tk.Button(root,text = labels[2], width = 20, height = 5, state = 'disabled')
self.binButton = tk.Button(root,text = labels[3], width = 20, height = 5, state = 'disabled')
self.plotButton = tk.Button(text = labels[3], width = 40, height = 5, state = 'disabled')
self.calibButton.grid(row = 0, column = 0)
self.bgButton.grid(row=0,column=1)
self.rawButton.grid(row=0,column=2)
self.binButton.grid(row=1,column=0)
self.plotButton.grid(row=1,column=1,columnspan = 2)
self.bgButton.configure(command=self.call_bgFrame)
root.mainloop()
def call_bgFrame(self):
self.background = bgFrame()
self.rawButton.config(state = 'normal')
app = MainClass()
我还需要更改其他一些内容,但是我尝试使您的代码尽可能与原始代码相似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.