如何在Tkinter中向Button命令传递参数?
假设我们正在使用tkinter应用程序,并且有一些按钮需要拉出某些窗口或事件。为了使按钮完全功能正常,我们可以将一些参数作为命令值传递。
命令是Button的属性,它将函数名称作为值。函数定义了特定事件的工作方式。
让我们首先创建一个按钮,并通过传递参数到其命令属性来添加一些事件。
示例
在这个例子中,我们将创建一个窗口和一个按钮,该按钮将立即关闭窗口。
# 导入所需库
from tkinter import *
# 创建一个实例化的tkinter帧或窗口
win= Tk()
# 设置标题
win.title("Button Command Example")
# 设置geometry
win.geometry("600x300")
# 创建窗口的标签
Label(win, text= "Example", font= ('Times New Roman bold',
20)).pack(pady=20)
# 定义一个函数
def close_event():
win.destroy()
# 创建一个按钮,并将参数作为函数名称传递到命令中
my_button= Button(win, text= "Close", font=('Helvetica bold', 20),
borderwidth=2, command= close_event)
my_button.pack(pady=20)
win.mainloop()
输出
通过运行上面的代码,我们可以将函数作为参数传递给Button命令。
点击“关闭”按钮,它将关闭窗口。