2017-03-09 86 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