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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM