2016-10-10 37 views
0

我有這段代碼,其中按下三個按鈕中的每一個,label2文本應記錄它們的狀態。Tkinter:__init__中的實例無法識別

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 因爲五個小工具在初始化定義推出的每一個都不能確認爲結果instances定義。因此print type(self.label2)返回NoneType

爲什麼發生?任何想法將不勝感激。

回答

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) 
+0

它很有效。謝謝。 – user3060854

相關問題