2017-03-09 57 views
0

正如标题所说,我想删除一个按钮,当它被点击。我已经尝试了许多不同的风格,这一次似乎是最简单的,但我不断收到错误:如何设置一个Tkinter按钮来删除一次点击?

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() 

回答

2

Store中的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() 
+1

的'elif的用户名= self.username:'是多余的,因为前述的条件式是其** **确切相反在这种情况下'否则:'是所有这是必要的。似乎这只是常识...... – martineau

+1

@马蒂诺,让我们把它留给OP的良知吧。感谢讽刺和\t 明显增加。 (: – CommonSense

+0

是的,我认为马蒂诺是正确的,我只是尽量让它尽可能具体,以消除任何潜在的错误,并且非常感谢你@CommonSense,我还是很新的,所以这真的很有帮助。 BTW是否知道如何将回车键连接到初始提交按钮,我发现所有的答案似乎都不起作用 self.button = Button(self.root,text =“SUBMIT”, highlightbackground =“green”,width = 48,command = selfcorrect) self.button.pack() self.button.bind(“”,command = selfcorrect) 你认为最好的是什么? – gmonz