2017-02-23 22 views
0

我正在使用Python製作一個簡單的小型點擊遊戲。這是目前我所擁有的:如何調用不同函數中定義的Tkinter標籤?

from tkinter import * 

x = [0] 
y = [1] 

class Game: 
    def __init__(self, master): 
     master.title('Game') 

     Amount = Label(master,text=x[0]) 
     Amount.pack() 

     Butt = Button(master,text='Press!',command=self.click) 
     Butt.pack() 

    def click(self): 
     x[0] = x[0] + y[0] 
     Amount.config(root,text=x[0]) 
     print(x[0]) 

root = Tk() 
root.geometry('200x50') 
game = Game(root) 
root.mainloop() 

當我運行這個時,它告訴我'數量'沒有在click函數中定義。我知道這是因爲它是在不同的功能中定義的。我想知道如何製作,因此點擊功能可以識別「金額」。

回答

1

您應該將您的金額定義爲數據成員(每個實例都有其值)或靜態成員(與所有類實例相同的值)。

我會去與數據成員。

要將其用作數據成員,您應該使用self.Amount

所以,這是你所需要的:

from tkinter import * 

x = [0] 
y = [1] 

class Game: 
    def __init__(self, master): 
     master.title('Game') 

     self.Amount = Label(master,text=x[0]) 
     self.Amount.pack() 

     Butt = Button(master,text='Press!',command=self.click) 
     Butt.pack() 

    def click(self): 
     x[0] = x[0] + y[0] 
     self.Amount.config(text=x[0]) 
     print(x[0]) 

root = Tk() 
root.geometry('200x50') 
game = Game(root) 
root.mainloop() 

自我是你的類的方法之間共享,這樣你就可以通過它訪問量變量。

+0

我試過這個,並收到以下錯誤:Tkinter回調中的異常; _tkinter.TclError:未知選項「-class」 –

+0

@MarkCostello,將行固定到'self.Amount.config(text = x [0])',這應該工作。 –

+0

我的程序與您編輯的完全一樣,它仍然給我「未知選項」 - 類「錯誤。 –

相關問題