Reputation: 358
What I am trying to do:
I want the button Confirmar
to disappear once it is clicked, for that I redirected it to the function dConfirm
which is supposed to trigger the destroy process.
What is happening:
The button is defined in a different function from the destroy process, so it is returning a not defined error.
My code:
def dSim():
btn3=Button(janela, text= "Hipertensao arterial", command = add1)
btn3.place(x = 80, y = 219)
btn4=Button(janela, text= "Pedras nos rins", command = add2)
btn4.place(x = 200, y = 219)
btn5=Button(janela, text= "Osteoporose", command = add3)
btn5.place(x = 295, y = 219)
btn6=Button(janela, text= "Colesterol elevado", command = add4)
btn6.place(x = 378, y = 219)
btn7=Button(janela, text= "Esclerose multipla", command = add5)
btn7.place(x = 492, y = 219)
btn.destroy()
btn2.destroy()
lb7=Label(janela, text= "Selecione as suas doencas:", font = ("Verdana", "14"))
lb7.place(x = 185, y = 190)
btn8=Button(janela, text= "Confirmar", command = dConfirm)
btn8.place(x = 80, y = 240)
def dNao():
lb5=Label(janela, text=Gperf, font = ("Verdana", "14"))
lb5.place(x = 80, y = 165)
btn.destroy()
btn2.destroy()
lb6=Label(janela, text="E perfeitamente saudavel, otimo!", font = ("Verdana", "14"))
lb6.place(x = 185, y = 190)
def dConfirm():
btn8.destroy()
Upvotes: 0
Views: 257
Reputation: 4407
You have three options:
btn8
is a local variable, so you cannot refer to it outside its scope. You can make it global.
Instead of directly calling dConfirm()
, pass to it the button instance using a lambda
like this:
btn8 = Button(janela, text="Confirmar", command=lambda: dConfirm(btn8))
and change the function definition to def dConfirm(btn8):
(I would prefer this if you don't want to move to option 3 and modify your code)
If you are using classes, make it an instance of the class by using self.btn8
and then destroy it by using self.btn8.destroy()
.
Upvotes: 3
Reputation: 3117
#1 You can try this:
import tkinter as tk
root = tk.Tk()
frame = tk.Frame(root)
frame.grid(row=0, column=0, padx=4, pady=4)
# destroy the button on dConfirm function call
def dConfirm():
btn8.destroy()
# Declare btn8 outside of the two function
btn8 = tk.Button(frame, text="Confirmar", command=dConfirm)
# Place btn8 inside the function you want
def dSim():
btn8.grid(row=0, column=0, padx=4, pady=4)
dSim()
root.mainloop()
#2 You can also try this (In my opinion this is better):
import tkinter as tk
class MainWindow:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.frame.grid(row=0, column=0, padx=4, pady=4)
self.dSim()
def dConfirm(self):
self.btn8.destroy()
def dSim(self):
self.btn8 = tk.Button(self.frame, text="Confirmar", command=self.dConfirm)
self.btn8.grid(row=0, column=0, padx=4, pady=4)
def main():
root = tk.Tk()
app = MainWindow(root)
root.mainloop()
if __name__ == '__main__':
main()
Upvotes: 1