2017-08-19 38 views
0

並感謝您傾聽...併爲我的糟糕英語感到抱歉。 我有一個簡單的Python腳本的問題,我不知道如何粉碎我的頭。帶參數,類和tkinter的Python noob

這就是代碼。是非常簡單和無用(我正在學習python,但我的編程技能是embarissing)。

import tkinter as tk 

class hello: 
    button_state = [0,0,0,0,0,0,0,0,0] 
    def __init__(self): 
     self.root = tk.Tk() 
     self.button = tk.Button(self.root, text=self.button_state[0], 
              command=self.check(0)) 
     self.button.pack() 
    def check(self,x): 
     if x == 0: 
      self.button_state[x] = 1 
      self.button.config(text=self.button_state[x]) 

app = hello() 
app.root.mainloop() 

和錯誤:

AttributeError: 'hello' object has no attribute 'button' 

我不知道爲什麼,如果我使用標籤的問題不存在」。我嘗試和嘗試,我認爲錯誤是在參數調用按鈕命令?

感謝提前:)

回答

0

您在初始化使用命令= self.check(0)。在check()中使用self.button.config。但是對象中沒有這個屬性(self.button)。也許,這段代碼可以幫助你。此外,在招呼你使用一個類屬性button_state - 你必須明白這一點:看https://docs.python.org/2/tutorial/classes.html(#誤用一類變)

import Tkinter as tk 

class hello: 
    button_state = [0,0,0,0,0,0,0,0,0] 
    def __init__(self): 
     self.root = tk.Tk()   
     self.button = tk.Button(self.root, text=self.button_state[0], command=self.check(0)) 
     self.button.config(text=self.button_state[0]) 
     self.button.pack() 

    def check(self,x): 
     if x == 0: 
      self.button_state[x] = 1 

app = hello() 
app.root.mainloop() 
0

當你的程序在第一次運行時,它運行由self.button的提供的功能命令。因爲你還沒有打包你的self.button,所以在這個函數中調用它會引發錯誤。要防止初始自動功能調用,您可以使用lambda。這將確保該函數僅在您使用self.button時纔會調用。

只要改變你的這部分代碼:

command=self.check(0) 

要這樣:

command= lambda x=0: self.check(x)