我希望我的程序以这样的方式运行:一旦用户按下Info按钮,一个名为GameInfoLabel
的标签就会由于Info按钮的命令而显示出来。在相同的条件下(如果按下了Info按钮),我想添加一个Back按钮来删除/销毁GameInfoLabel
我试图在下面的代码中实现这一点,但我得到了消息
NameError: name 'GameInfoLabel' is not defined.
from tkinter import *
root = Tk()
root.title("Game Menu")
root.geometry("1920x1080")
root.resizable(True, True)
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").pack()
BackInfoButton = Button(root, text = "Back", command = QuitGameInfo).pack()
RulesNotepad.close()
button3 = Button(root, text = "Info", command = GameInfo, width = "20", height = "3").pack()
root.mainloop()
该错误是由于
GameInfoLabel
是GameInfo()
内的局部变量,在QuitGameInfo()
内无法访问该变量您可以通过将
GameInfoLabel
声明为全局或通过参数将其传递给QuitGameInfo()
来修复此错误。这同样适用于BackInfoButton
但是,您需要解决另一个问题:
GameInfoLabel
和BackInfoButton
都是None
,因为它们是pack()
的结果下面是使用全局解决方案修改的代码:
但是,我建议使用一个框架来保存
GameInfoLabel
和BackInfoButton
,框架最初是隐藏的。单击Info按钮时,显示帧。单击“后退”按钮时,隐藏帧如acw1668的注释所述
GameInfoLabel
是GameInfo()
方法的局部。这意味着一旦此方法完成运行,其中声明的任何内容都将停止存在通常的解决方案是向函数传递/返回变量以获得结果,例如,游戏信息可以返回标签,但是,由于您希望在事件发生时自动调用这些函数,例如,按下按钮,这并不容易
我相信解决问题的最简单方法是全局声明
GameInfoLabel
变量(在全局范围内),这并不总是最佳编码实践,但我不确定tkinter是否能够将变量参数传递给事件处理程序,这可能会很复杂正如acw1668所提到的,您可以在初始化
Label(...)
返回的新标签上立即调用.pack()。然后包装不会返回标签,因此我们会单独返回这应该行得通,仔细阅读一下
相关问题 更多 >
编程相关推荐