[Python][tkinter]使用Button中的command呼叫函數 Use Button Command Call Function

This example shows how to use "command" in button to call a function with or without parameters 1. Import tkinter 2. build a window named "win". 3. window format 1: title() 4. window format 2: geometry() determine size and initial position(x,y) 5. window format 3: maxsize() set max size of a window 6. Build Label component and give a string to text 7. Build close_win function to end the window 8. Build add_label_num function to deliver paramters for increasing the text of the label and use lbl.config to change the label status 9. Build Button component and give a string to text, and use command to call the function 10. Build Button component and give a string to text, and use command to call the function with parameters 11. Use pack to arrange Button on bottom side 12. Use pack to arrange Button on left side 13. Use pack to arrange Build Label on right side 14. Use mainloop() to keep window running for monitoring and handling events 這個範例說明如何使用Button中的command呼叫有參數以及無參數的函數。


#1. 引入tkinter
#2. 建立一個名為win的新視窗
#3. 視窗格式: 標題 Title()
#4. 視窗格式: 設定視窗啟動時的大小與位置 geometry("寬x長+x位移+y位移")
#5. 視窗格式: 設定視窗最大尺寸 maxsize(int長,int寬)
#6. 建立Label元件,按鍵文字 Text = "0"
#7. 建立函數close_win函數: 結束win視窗
#8. 建立函數add_label_number(num): 傳遞參數,可以增加Label中的Text數字,使用config()改變Label狀態
#9. 建立Button元件,按鍵文字 Text = "",使用command呼叫函數
#10. 建立Button元件,按鍵文字 Text = "",使用command中的lambda在按鈕事件中傳遞引數
#11. Button元件布局 pack(side='botton') 靠下
#12 Button元件布局 pack(side='left') 靠左
#13. Label元件布局 pack(side='right') 靠右
#14. mainloop()在使用者關閉視窗之前持續偵測視窗並處理事件
             
import tkinter as tk
win = tk.Tk()
win.title("tkinter button test")
win.geometry("400x400+200+200")
win.maxsize(800,800)
def close_win():
    win.destroy()
def add_label_num(num):
    counter=int(str(lbl['text']))
    counter+=num
    lbl.config(text=str(counter))
close_btn=tk.Button(win,text="Close"command=close_win)
add_btn=tk.Button(win,text="Add",command=lambda:add_label_num(2))

close_btn.pack(side="bottom")
add_btn.pack(side='left')
lbl=tk.Label(win,text="0")
lbl.pack(side='right')
win.mainloop()



We will share more tutorial videos with people who want to learn LabVIEW and Python welcome to subscribe this channel. 未來會陸續更新影片,讓想學習LabVIEW和Python的朋友可以看影片學習,歡迎訂閱此頻道。 其他網址/related websites: https://labview-tech.blogspot.com/ https://fishark.pixnet.net/blog email: jacklee3633@gmail.com  Line: lvnet

留言

這個網誌中的熱門文章

使用VS code開發Python程式 - Matplotlib繪圖

使用Pycharm開發Python程式與用Matplotlib繪圖