[英]How do I call upon Tkinter labels defined in a different function?
我正在使用Python制作一個簡單的小點擊游戲。 這是我目前擁有的:
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函數中未定義“金額”。 我知道這是因為它是在不同的函數中定義的。 我想知道如何制作,以便點擊功能識別“金額”。
您應該將金額定義為數據成員(每個實例都有其值)或靜態成員(所有類實例具有相同的值)。
我會和數據成員一起去。
為了將其用作數據成員,應使用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()
self在類方法之間共享,因此您可以通過它訪問Amount變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.