Python Button clockOK()

from tkinter import *
root=Tk()
root.title("Tk GUI")
label=Label(root, text="Hello World!")
button=Button(root, text="OK")
label.grid(column=0,row=0)
button.grid(column=1,row=0)
root.mainloop()

目前這個按鈕按下去不會有反應, 因為我們還沒有幫它設定事件處理函數. 在下面範例中, 我定義了一個按鈕事件處理函數 clickOK() 來處理 OK 鍵被按事件, 並設定了一個全域變數 count 來記錄 OK 鍵被按了幾次, 當 OK 被按時, count 會增量, 並且透過呼叫元件的 configure() 或 config() 函數來更改標籤元件的文字內容 (text 屬性) :

from tkinter import *
root=Tk()
root.title("Tk GUI")
label=Label(root, text="Hello World!")
count=0
def clickOK():
    global count
    count=count + 1
    label.configure(text="Click OK " + str(count) + " times")
button=Button(root, text="OK", command=clickOK)
label.pack()
button.pack()
root.mainloop()




注意, 事件處理函數與 GUI 元件之間是透過 command 參數來綁定的. 另外上面也用到了 Python 內建函數 str() 來將數值類型的 count 轉成字串類型.

留言

這個網誌中的熱門文章

python serial 模組使用方法 #1

USB HID 教學 #1(轉載)

USB HID 教學 #2 (轉載)