正如标题所说,我想在点击按钮时删除按钮。我尝试了很多不同的风格,这个似乎是最简单的,但我不断收到错误:
line 34, in incorrect
button2.Button.destroy()
NameError: name 'button2' is not defined
当尝试如下所示的不同方法时,这一个:
NameError: name 'button2' is not defined
尝试在开头定义时,我会收到此错误:
UnboundLocalError: local variable 'button2' referenced before assignment
非常感谢任何帮助,谢谢。
我的代码:
from tkinter import *
class Application(object):
def __init__(self):
self.root = Tk()
self.root.configure(bg="darkorchid1", padx=10, pady=10)
self.root.title("WELCOME TO THIS PROGRAM)")
self.username = "Bob"
program = Label(self.root, text="MY PROGRAM", bg="lightgrey", fg="darkorchid1")
program.pack()
label0 = Label(self.root, text="ENTER USERNAME:", bg="purple", fg="white", height=5, width=50)
label0.pack()
self.entry = Entry(self.root, width=25)
self.entry.configure(fg= "white",bg="grey20")
self.entry.pack()
button = Button(self.root, text="SUBMIT", highlightbackground="green", width=48, command=self.correct)
button.pack()
def correct(self):
username = self.entry.get()
if username == self.username:
button1 = Button(self.root, text='LOGIN', highlightbackground="green", width=28, command=self.root.destroy)
button1.pack()
elif username != self.username:
button2 = Button(self.root, text="INCORRECT- CLICK TO DIMISS THIS MESSAGE", highlightbackground="red", width=48, command=self.incorrect)
button2.pack()
def incorrect(self):
button2.destroy()
app=Application()
mainloop()
答案 0 :(得分:2)
将您的button
- 变量存储在一个类中,或者只是将它们传递给您的函数。由于button2
超出范围,您遇到了问题!
请改为尝试:
def correct(self):
username = self.entry.get()
if username == self.username:
self.button1 = Button(self.root, text='LOGIN', highlightbackground="green",
width=28, command=self.root.destroy)
self.button1.pack()
elif username != self.username:
self.button2 = Button(self.root,
text="INCORRECT- CLICK TO DIMISS THIS MESSAGE",
highlightbackground="red", width=48,
command=self.incorrect)
self.button2.pack()
def incorrect(self):
self.button2.destroy()