tkinter中如何给控件的command传递参数

踩坑了,务必记录一下。

问题

在tkinter程序中,Button绑定的函数是不能带返回值的,编写代码时command=后边的函数名不能带有括号(不能直接执行)。

那如果想要传入带参数的函数该怎么办呢?(必须带括号的函数)

解决

非循环

假如在程序中,你会改变Entry中的值,然后Button需要读取这个值,那么直接使用lambda函数:

1
2
3
4
5
# 此为示例代码
import tkinter as tk

e = tk.Entry(window).pack()
b = tk.Button(window, text="xx", command=lambda: e.get()).pack()

循环

假如在程序中,你需要在Button中操作一个循环变量,那么不能向上边一样直接lambda,需要小小操作一番:

1
2
3
4
5
6
7
8
9
# 此为示例代码
import tkinter as tk
import webbrowser

links = [url1, url2, url3]

# 创建三个按钮,分别调用浏览器打开url1,url2,url3
for i in range(3):
b = tk.Button(window, text="xx", command=lambda i=i: webbrowser.open(links[i])).pack()

参考:https://www.zhihu.com/question/399386753