tkinter 按钮响应函数传值

tkinter 中的Button组件的响应函数如何传入参数,可能非常困扰新手,这里记录一下。

步骤:

1. 写好响应函数(形参设置好)

2. 在Button command 设置形式:command = lambda : function_name(params...)

如果不加lambda,会直接调用函数,即:未点击直接就响应。

例子:

 1 # -*- coding: utf-8 -*-
 2 # @Author  : yocichen
 3 # @Email   : yocichen@126.com
 4 # @File    : sendDataToBtnFunc.py
 5 # @Software: PyCharm
 6 # @Time    : 2019/11/20 16:04
 7 
 8 import tkinter as tk
 9 from tkinter import messagebox as msg
10 
11 def test_func(string):
12     msg.showinfo(title='按钮被点击', message='传入参数:'+string)
13 
14 def show_btn():
15     string  = '弘毅明德, 笃学创新'
16     root = tk.Tk()
17     root.title('测试按钮响应函数传值')
18     root.geometry("200x100")
19     test_btn = tk.Button(text='点一下,就点一下', master=root, bg='#CC33CC', command=lambda : test_func(string))
20     test_btn.pack()
21     root.mainloop()
22 
23 if __name__ == '__main__':
24     show_btn()

效果:

 参考

https://blog.csdn.net/guge907/article/details/23291763

原文地址:https://www.cnblogs.com/yocichen/p/11898788.html