Python學習(二):使用TKinter進行GUI程序設計

小例子

Tkinter(T-K-Inter)模塊包含建立各類GUI(圖形用戶界面設計)的類。Tk建立一個放置GUI小構件的窗口(便可視化組件)。python

from tkinter import *   # 導入tkinter模塊

window = Tk()   # 建立一個窗口(父容器)
label = Label(window, text="Welcome to Python")     # 建立一個標籤(小構件類,其第一個參數永遠是父容器)
button = Button(window, text="Click Me")     # 建立一個按鈕
label.pack()     # 把標籤放在窗口中(使用一個包管理器,將label放在容器中)
button.pack()     # 把按鈕放在窗口中

window.mainloop()      # 建立一個事件循環,這個事件循環持續處理事件,直到關閉主窗口
 

 

處理事件

一個Tkinter小構件能夠與一個函數綁定,當事件發生時被調用函數

from tkinter import *


class ProcessButtonEvent:
    def __init__(self):
        window = Tk()
        okButton = Button(window, text="OK", fg="red", command=self.processOk)  # 將okButton綁定到processOK函數,當按鈕被單擊時,這個函數將被調用。fg 指定按鈕前景色,默認爲黑色
        cancelButton = Button(window, text="CANCEL", fg="red", bg="yellow", command=self.processCancel)  #bg 指定按鈕背景色,默認爲灰色

        okButton.pack()
        cancelButton.pack()

        window.mainloop()

    def processOk(self):
        print("Ok button is clicked")

    def processCancel(self):
        print("Cancel button is clicked")


ProcessButtonEvent()
 

  程序定義了兩個函數,processOk和processCancel,當建立這些函數時,這些函數被綁定到按鈕。這些函數被稱爲回調函數處理器oop

  定義一個類來建立GUI和處理GUI事件有兩個優勢。首先,未來能夠重複使用這個類;其次,將全部函數定義爲方法可讓它們訪問類中的實例數據域。spa

相關文章
相關標籤/搜索