天天看點

使用 Tkinter 建立桌面應用程式

作者:MikoAndCody

Tkinter 是一個内置的 Python GUI 庫,用于建立獨立于平台的圖形使用者界面 (GUI)。它是一個跨平台、輕量級且易于使用的庫,使其成為開發桌面應用程式的理想選擇。Tkinter 提供了一組标準的小部件和工具來建立圖形使用者界面。這些小部件包括按鈕、标簽、文本框、畫布、菜單欄等等。在本文中,我們将探索 Tkinter 庫的特性和功能以及一些代碼示例。

使用 Tkinter 建立桌面應用程式

安裝

Tkinter 包含在 Python 标準庫中,是以您無需單獨安裝它。您可以通過運作以下代碼來檢查安裝:

import tkinter
print(tkinter.TkVersion)           

這将顯示目前安裝的 Tkinter 庫的版本。

建立一個簡單的 GUI 應用程式

讓我們從建立一個簡單的 GUI 應用程式開始。我們将建立一個視窗帶有标簽和單擊按鈕列印“Hello World!”。

import tkinter as tk

def print_hello():
    print("Hello World!")

root = tk.Tk()
root.title("My Application")

label = tk.Label(root, text="Welcome to my application")
label.pack()

button = tk.Button(root, text="Click me!", command=print_hello)
button.pack()

root.mainloop()           

此代碼将建立一個帶有标簽和按鈕的視窗。單擊該按鈕時,它将列印“Hello World!” 。函數tk.Tk()用于建立視窗,title()方法用于設定視窗的标題。函數tk.Label()用于建立标簽,text參數用于設定标簽文本。該pack()方法用于将标簽添加到視窗。同樣,tk.Button()函數用于建立按鈕,text參數用于設定按鈕文本。command參數用于指定單擊按鈕時要執行的功能。

建立文本框

Tkinter 提供了一個Text元件來建立一個文本框。該Text小部件可用于顯示和編輯文本。

import tkinter as tk

root = tk.Tk()
root.title("My Application")

label = tk.Label(root, text="Enter your name:")
label.pack()

text_box = tk.Text(root, height=1, width=20)
text_box.pack()

root.mainloop()           

此代碼将建立一個帶有标簽和文本框的視窗。該tk.Text()函數用于建立文本框, height和width用于設定文本框的大小。pack()方法用于将文本框添加到視窗。

添加菜單欄

Tkinter 提供了一個 Menu元件來建立一個菜單欄。該Menu小部件可用于建立菜單和菜單項。

import tkinter as tk

def open_file():
    print("File opened")

def save_file():
    print("File saved")

root = tk.Tk()
root.title("My Application")

menu_bar = tk.Menu(root)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Open", command=open_file)
file_menu.add_command(label="Save", command=save_file)
menu_bar.add_cascade(label="File", menu=file_menu)

root.config(menu=menu_bar)
root.mainloop()           

此代碼将建立一個帶有菜單欄的視窗。tk.Menu()函數用于建立菜單欄。tk.Menu()函數還用于建立菜單項,add_command()方法用于向菜單項添加指令。參數label用于設定菜單項的文本,command參數用于指定單擊菜單項時要執行的功能。add_cascade()方法用于向菜單欄添加菜單。

處理事件

在 Tkinter 中,可以使用bind()方法處理事件。bind()方法用于将事件綁定到函數。當事件發生時,執行指定的函數。

import tkinter as tk

def print_hello(event):
    print("Hello World!")

root = tk.Tk()
root.title("My Application")

button = tk.Button(root, text="Click me!")
button.pack()

button.bind("<Button-1>", print_hello)

root.mainloop()           

此代碼将建立一個帶有按鈕的視窗。bind()方法用于将Button-1事件綁定到print_hello()函數。單擊按鈕時将執行print_hello()。

結論

在本文中,我們探讨了 Tkinter 庫的基礎知識以及如何使用它來建立 GUI 應用程式。我們介紹了如何建立簡單的 GUI 應用程式、如何建立文本框、如何添加菜單欄以及如何處理事件。Tkinter 是一個多功能的庫,它提供了許多小部件和工具來建立強大的互動式 GUI 應用程式。使用 Tkinter,您可以建立在 Windows、Linux 和 macOS 上運作的桌面應用程式。對于想要使用 Python 建立桌面應用程式的初學者和有經驗的開發人員來說,這是一個絕佳的選擇。

繼續閱讀