[英]How to setup a Tkinter button to erase once clicked?
As the title says, I want to erase a button when it is clicked. 就像标题中所说的,我想在单击按钮时删除它。 I have tried many different styles and this one seemed to be the simplest, but I keep getting the error: 我尝试了许多不同的样式,这似乎是最简单的样式,但我不断收到错误消息:
line 34, in incorrect
button2.Button.destroy()
NameError: name 'button2' is not defined
and when trying a different method as shown below, this one: 当尝试如下所示的另一种方法时,该方法:
NameError: name 'button2' is not defined
When trying to define it in the beginning I would receive this error: 在一开始尝试定义它时,我会收到此错误:
UnboundLocalError: local variable 'button2' referenced before assignment
Any help would be greatly appreciated, thank you. 任何帮助将不胜感激,谢谢。
My code: 我的代码:
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()
Store your button
-variables within a class or just pass them to your functions. 将您的button
变量存储在类中,或仅将它们传递给函数。 You got problems because of your button2
is out of scope! 由于button2
超出范围,您遇到了问题!
Try this instead: 尝试以下方法:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.