2 回答

TA貢獻1854條經驗 獲得超8個贊
該錯誤是由于這GameInfoLabel是內部的局部變量GameInfo()并且在內部不可訪問QuitGameInfo()。
您可以通過聲明GameInfoLabel為全局或將其傳遞給QuitGameInfo()via 參數來修復此錯誤。同樣適用于BackInfoButton。
但是,您需要解決另一個問題: 和GameInfoLabel都是BackInfoButton因為None它們是 的結果pack()。
下面是使用全局解決方案修改后的代碼:
from tkinter import *
root = Tk()
root.title("Game Menu")
root.geometry("1920x1080")
root.resizable(True, True)
def QuitGameInfo():
GameInfoLabel.destroy()
#BackInfoButton['state'] = NORMAL # why ??? Should it be destroyed as well?
BackInfoButton.destroy()
def GameInfo():
global GameInfoLabel, BackInfoButton
with open("GameInfo.txt",'r') as RulesNotepad:
Rules = RulesNotepad.read()
GameInfoLabel = Label(root, text = Rules, fg = "blue", bg = "red", height = "14", width = "140")
GameInfoLabel.pack()
BackInfoButton = Button(root, text = "Back", command = QuitGameInfo)
BackInfoButton.pack()
Button(root, text = "Info", command = GameInfo, width = "20", height = "3").pack()
root.mainloop()
不過,我建議使用框架來固定框架GameInfoLabel,并且BackInfoButton框架最初是隱藏的。單擊按鈕時Info,顯示框架。單擊按鈕時Back,隱藏框架。
from tkinter import *
root = Tk()
root.title("Game Menu")
root.geometry("1920x1080")
root.resizable(True, True)
def GameInfo():
with open("GameInfo.txt",'r') as RulesNotepad:
Rules = RulesNotepad.read()
GameInfoLabel.config(text=Rules)
info_frame.pack() # show the game info frame
Button(root, text="Info", command=GameInfo, width="20", height="3").pack()
# create the game info frame but don't show it initially
info_frame = Frame(root)
GameInfoLabel = Label(info_frame, fg="blue", bg="red", height="14", width="140")
GameInfoLabel.pack()
Button(info_frame, text="Back", command=info_frame.pack_forget).pack()
root.mainloop()

TA貢獻1805條經驗 獲得超10個贊
GameInfoLabel該方法是本地的GameInfo()。這意味著一旦該方法完成運行,其中聲明的任何內容都將不再存在。
通常的解決方案是將變量傳遞/返回到函數以獲取結果,例如您的游戲信息可以返回標簽,但是由于您希望在事件發生時自動調用這些函數,例如按下按鈕,所以這并不那么容易。
我相信解決您的問題的最簡單的解決方案是GameInfoLabel全局聲明變量(在全局范圍內),這并不總是最好的編碼實踐,但我不確定 tkinter 是否能夠將變量參數傳遞給事件處理程序,這可以變得復雜。
另外,正如 acw1668 所提到的,您可以在從初始化返回的新標簽上立即調用 .pack() Label(...)。然后打包不會返還標簽,因此我們單獨進行返還。
這應該有效,請仔細閱讀。
from tkinter import *
root = Tk()
root.title("Game Menu")
root.geometry("1920x1080")
root.resizable(True, True)
# Declare any global UI Components
GameInfoLabel = None # Dont set a Label yet
def QuitGameInfo():
GameInfoLabel.destroy()
BackInfoButton['state'] = NORMAL
def GameInfo():
RulesNotepad = open("GameInfo.txt",'r')
Rules = RulesNotepad.read()
GameInfoLabel = Label(root, text = Rules, fg = "blue", bg = "red", height = "14", width = "140")
GameInfoLabel.pack()
BackInfoButton = Button(root, text = "Back", command = QuitGameInfo).pack()
RulesNotepad.close()
button3 = Button(root, text = "Info", command = GameInfo, width = "20", height = "3")
button3.pack()
root.mainloop()
添加回答
舉報