[Python] 使用 CustomTkinter 建立圖形化使用者介面

Tkinter 是 Python 標準的圖形介面套件,缺點就是有點「復古」,還好網路上的大神做了 CustomTkinter 這款基於 Tkinter 的圖形介面套件:

安裝

    
pip install customtkinter
    

起手式 - 建立一個視窗

比較常見的做法是自訂一個類別,繼承 CustomTkinter 的主視窗,啟動時執行 mainloop:
    
import customtkinter


class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()


if __name__ == "__main__":
    app = App()
    app.mainloop()
    

不過如果要簡單的話可以這樣:
    
import customtkinter


app = customtkinter.CTk()

if __name__ == "__main__":
    app.mainloop()
    


視窗常用設定

(接下來都會使用第二種方式做示範,平時使用第一種方式開發時改為 self 即可,例如從 app.title,改為 self.title)
    
import customtkinter


app = customtkinter.CTk()  # 建立主畫面

app.iconbitmap("C:/Users/ruyut/Pictures/r2.ico")  # 設定左上角圖示
app.title("Ruyut App")  # 標題

app.geometry("400x300")  # 寬 x 高
app.geometry("+800+600")  # 設定座標(+x+y)
app.geometry("400x300+800+600")  # 同時設定 寬高和座標

# 寬不能拖曳改變大小, 高可以改變
app.resizable(False, True)
    

按鈕

    

def button_function():
    print("button clicked")


button = customtkinter.CTkButton(master=app, text="這是一個按鈕", command=button_function)
button.place(relx=0.5, rely=0.5, anchor=customtkinter.CENTER) # 位置在中心
# button.grid(padx=0, pady=0) # 指定座標
    


如果要設定按鈕寬高要在一開始就設定
    
button = customtkinter.CTkButton(master=app, text="這是一個按鈕", command=button_function, width=300, height=300)
    



參考資料:
GitHub - TomSchimansky/CustomTkinter
CustomTkinter Python - tkinter — Python interface to Tcl/Tk

留言