我不是程序员,只是一个爱好者,所以如果你能告诉我_1756108,我会很高兴 .
What I want:
我想用tkinter创建一个具有“新游戏”,“设置”和“退出”按钮的菜单,如果我点击“退出”按钮,我想要一个“你确定吗?”弹出窗口有“是”和“否”按钮,如果我点击“否”按钮,我想破坏“你确定吗?”弹出窗口 .
What's happening:
“新游戏”和“设置”按钮正是我想要的,但是当我点击“退出”按钮时,我得到了“你确定吗?”弹出窗口,我收到此错误:
name 'varAreYouSureToplevel' is not defined
If this is NOT the correct way, please let me know how it's usually made.
我正在学习如何编写类,当我尝试在类中使用Tkinter时,这对我来说有点混乱 .
If you have a solution for this (using Tkinter root and Toplevel) WITHOUT writing classes, then I would be very glad to see it!
我正在使用 Python 3.4
谢谢您的帮助!
这是我的代码:
from tkinter import *
import os
class classMainMenu(Frame):
def __init__(self, varRoot):
Frame.__init__(self, varRoot)
self.grid()
self.funcMainMenu()
def funcMainMenu(self):
self.varNewGameButton = Button(self, text="New Game", command=self.funcNewGame)
self.varNewGameButton.grid(row=0, column=0)
self.varSettingsButton = Button(self, text="Settings", command=self.funcSettingsMenu)
self.varSettingsButton.grid(row=1, column=0)
self.varExitButton = Button(self, text="Exit", command=self.funcExit)
self.varExitButton.grid(row=2, column=0)
def funcNewGame(self):
self.varNewGameButton.destroy()
self.varSettingsButton.destroy()
self.varExitButton.destroy()
print("New Game")
def funcSettingsMenu(self):
self.varNewGameButton.destroy()
self.varSettingsButton.destroy()
self.varExitButton.destroy()
print("Settings")
def funcExit(self):
self.varAreYouSureToplevel = Toplevel(self)
self.varAreYouSureToplevel.title("Are you sure?")
self.varAreYouSureTextLabel = Label(varAreYouSureToplevel, text="Are you sure you want to exit?") # HERE IT SAYS: NameError: name 'varAreYouSureToplevel' is not defined
self.varAreYouSureTextLabel.grid(row=3, column=0)
self.varAreYouSureYesButton = Button(varAreYouSureToplevel, text="Yes", command=self.funcExitToDesktop)
self.varAreYouSureYesButton.grid(row=4, column=0)
self.varAreYouSureNoButton = Button(varAreYouSureToplevel, text="No", command=self.funcDestroyToplevel)
self.varAreYouSureNoButton.grid(row=4, column=1)
def funcDestroyToplevel(self):
self.varAreYouSureToplevel.destroy
def funcExitToDesktop(self):
os._exit(1)
varRoot = Tk()
objectMainMenu = classMainMenu(varRoot)
objectMainMenu.mainloop()
2 回答
在
funcExit()
中你有例如Label(varAreYouSureToplevel)
(和Button
x2) .varAreYouSureToplevel
是self
的一个属性,但是你指的是没有self.
的属性,所以Python正在寻找全局命名空间,你得到你正在观察的错误 .将这三个陈述改为例如
Label(self.varAreYouSureToplevel
和Button(self.varAreYouSureToplevel
你的代码工作得很好 .
我建议使用消息框而不是创建另一个窗口 . 除非你想要的不仅仅是一个简单的是/否 .