Tkinter:__ init__中的实例无法识别

时间:2016-10-10 07:04:50

标签: 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", 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' object does not support item assignment ,因为 init 定义中启动的五个小部件中的每一个都未在结果中被识别为instances定义。因此print type(self.label2)会返回NoneType

为什么会这样?任何想法都将不胜感激。

1 个答案:

答案 0 :(得分:2)

这是因为在您的代码的这一部分:

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()方法的结果,并返回“无”。为了防止这种情况,请改为执行以下操作:

self.label1 = Label(frame, text="buttons", fg="black")
self.label1.grid(row=0)
相关问题