Python Tkinter:无法识别初始化中的实例
我有一个代码,其中按下三个按钮中的每一个,label2文本应该记录它们的状态Python Tkinter:无法识别初始化中的实例,python,tkinter,Python,Tkinter,我有一个代码,其中按下三个按钮中的每一个,label2文本应该记录它们的状态 from Tkinter import * class App: def __init__(self, master): self.state = [False, False, False] frame = Frame(master) frame.pack() self.label1 = Label(frame, text="buttons
from Tkinter import *
class App:
def __init__(self, master):
self.state = [False, False, False]
frame = Frame(master)
frame.pack()
self.label1 = Label(frame, text="buttons", fg="black").grid(row=0)
self.buttonR = Button(frame, text="RED", fg="red", command=self.controlR).grid(row=1, column=0)
self.buttonG = Button(frame, text="GREEN", fg="green", command=self.controlG).grid(row=1, column=1)
self.buttonB = Button(frame, text="BLUE", fg="blue", command=self.controlB).grid(row=1, column=2)
self.label2 = Label(frame, text="results", fg="black").grid(row=2)
def controlR(self):
self.state[0] = not self.state[0]
self.results()
def controlG(self):
self.state[1] = not self.state[1]
self.results()
def controlB(self):
self.state[2] = not self.state[2]
self.results()
def results(self):
color_list = ["RED", "GREEN", "BLUE"]
my_str = 'button '
for i in xrange(len(color_list)):
my_str += color_list[i]
if self.state[i] == False:
my_str += " is OFF \n"
else:
my_str += " is ON \n"
print my_str
print type(self.label2)
self.label2['text'] = my_str
root = Tk()
app = App(root)
root.mainloop()
root.destroy()
我得到的是TypeError:“NoneType”对象不支持项分配
因为在init定义中启动的五个小部件中的每一个在结果定义中都不会被识别为实例。因此,打印类型(self.label2)
返回NoneType
为什么会这样?如果您有任何想法,我们将不胜感激。这是因为在代码的这一部分:
self.label1 = Label(frame, text="buttons", fg="black").grid(row=0)
self.buttonR = Button(frame, text="RED", fg="red", command=self.controlR).grid(row=1, column=0)
self.buttonG = Button(frame, text="GREEN", fg="green", command=self.controlG).grid(row=1, column=1)
self.buttonB = Button(frame, text="BLUE", fg="blue", command=self.controlB).grid(row=1, column=2)
self.label2 = Label(frame, text="results", fg="black").grid(row=2)
您被分配了调用小部件的grid()
方法的结果,它返回“None”。为了防止这种情况,只需对每一个进行如下操作:
self.label1 = Label(frame, text="buttons", fg="black")
self.label1.grid(row=0)
这是因为在代码的这一部分:
self.label1 = Label(frame, text="buttons", fg="black").grid(row=0)
self.buttonR = Button(frame, text="RED", fg="red", command=self.controlR).grid(row=1, column=0)
self.buttonG = Button(frame, text="GREEN", fg="green", command=self.controlG).grid(row=1, column=1)
self.buttonB = Button(frame, text="BLUE", fg="blue", command=self.controlB).grid(row=1, column=2)
self.label2 = Label(frame, text="results", fg="black").grid(row=2)
您被分配了调用小部件的grid()
方法的结果,它返回“None”。为了防止这种情况,只需对每一个进行如下操作:
self.label1 = Label(frame, text="buttons", fg="black")
self.label1.grid(row=0)
成功了。谢谢,成功了。非常感谢。