我要做什么:
我希望按钮Confirmar
一旦被单击就消失,因此我将其重定向到了应该触发销毁过程的功能dConfirm
。
正在发生的事情:
该按钮的定义功能与销毁过程不同,因此返回的是未定义错误。
我的代码:
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()
答案 0 :(得分:3)
您有三个选择:
btn8
是 local 变量,因此您不能在其范围之外引用它。您可以将其设置为全局。
不是直接调用dConfirm()
,而是使用lambda
将按钮实例传递给它,如下所示:
btn8 = Button(janela, text="Confirmar", command=lambda: dConfirm(btn8))
并将函数定义更改为def dConfirm(btn8):
(如果您不想移至选项3并修改代码,我希望这样做)
如果您使用的是类,请使用self.btn8
将其作为类的实例,然后使用self.btn8.destroy()
将其销毁。
答案 1 :(得分:1)
#1 ,您可以尝试以下操作:
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 ,您也可以尝试一下(我认为这样更好):
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()