当变量调用函数并且函数包含变量时,如何从变量中调用函数?

时间:2020-06-30 18:33:33

标签: python python-3.x tkinter

这有点自相矛盾,但是我找不到解决方案。我的问题实际上是从一个Tkinter按钮开始自毁的:Button=Tk.button(root, text="Press me!", command=Button.destroy())

但是我收到错误NameError: name 'Button' is not defined,所以我想我不能使用它。然后,我尝试了:

import tkinter as Tk

root=Tk.Tk()

def DeleteButton():

    Button.destroy()

Button=Tk.button(root, text="Press me!", command=DeleteButton())

root.mainloop()

DeleteButton()包含变量Button,因此我必须将Button的声明放在函数之前。但是Button调用了该函数,因此该函数必须优先。请注意,我只有几个月使用Python的经验,所以我并不出色。

2 个答案:

答案 0 :(得分:1)

您可以使用lambda创建匿名函数。

Button = Tk.button(root, text="Press me!", command = lambda:Button.destroy())

答案 1 :(得分:0)

import tkinter as Tk

root=Tk.Tk()

def DeleteButton():
    Button.destroy()

Button=Tk.Button(root, text="Press me!", command=DeleteButton)
Button.pack()

root.mainloop()