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()
效果:
參考