Python 憑借其簡單性和多功能性,已經成為最流行的編程語言之一。被廣泛應用于從 web 開發到數據科學的各個領域。
在本教程中,我們將探索用于創建圖形用戶界面(GUIs)的 Python 內置庫:
Tkinter:無論你是初學者還是經驗豐富的開發人員,了解如何創建 Python GUI 都可以增強你構建交互式應用程序的能力。
Tkinter 是 Python 附帶的標準 GUI 工具包。它提供了一組用于創建圖形用戶界面的工具和小部件。
讓我們從一個基本的例子開始了解 Tkinter。打開你最喜歡的 Python 編輯器(我的是 Pycharm)并創建一個新文件,例如就叫 hello_tkinter.py。編寫以下代碼:
import tkinter as tkdef say_hello(): label.config(text="Hello, Tkinter!")# Create the main windowroot = tk.Tk()root.title("Tkinter Hello World")# Create a label widgetlabel = tk.Label(root, text="Welcome to Tkinter!")# Pack the label into the main windowlabel.pack(pady=10)# Create a button widgetbutton = tk.Button(root, text="Say Hello", command=say_hello)# Pack the button into the main windowbutton.pack(pady=10)# Start the Tkinter event looproot.mainloop()
輸出:
保存文件并運行它,你應該會看到一個帶有標簽和按鈕的窗口,點擊該按鈕將把標簽文本更改為"Hello, Tkinter!":
圖片
圖片
現在我們已經創建了一個簡單的 Tkinter 應用程序,讓我們深入研究一些基本概念和小部件。
小部件是 Tkinter GUI 的構建模塊。它們可以是按鈕、標簽、輸入字段等等。比如在前面的例子中我們已經使用了 Label 和 Button 小部件。
Entry Widget 允許用戶輸入一行文本。現在讓我們擴展我們的 Hello, Tkinter! 的示例,通過添加一個 Entry Widget 來獲取用戶名:
import tkinter as tkdef say_hello(): name = entry.get() label.config(text=f"Hello, {name}!")# Create the main windowroot = tk.Tk()root.title("Tkinter Hello World")# Create a label widgetlabel = tk.Label(root, text="Welcome to Tkinter!")# Pack the label into the main windowlabel.pack(pady=10)# Create a button widgetbutton = tk.Button(root, text="Say Hello", command=say_hello)# Pack the button into the main windowbutton.pack(pady=10)# Create an entry widgetentry = tk.Entry(root)# Pack the entry widget into the main windowentry.pack(pady=10)# Start the Tkinter event looproot.mainloop()
通過這個修改,用戶可以在 Entry Widget 中輸入他們的名字,點擊 Say Hello 按鈕將會向他們打招呼。
演示:
圖片
圖片
Tkinter 提供多種幾何管理器來組織窗口內的小部件。我們前面使用的 pack() 方法就是其中之一。此外,你還可以使用 grid() 和 place() 進行更復雜的布局。
你可以使用 grid() 方法創建類似網格的布局。讓我們在我們的示例中加入網格布局:
# ...# Pack the label and entry widgets into the main window using the grid layoutlabel.grid(row=0, column=0, pady=10)entry.grid(row=1, column=0, pady=10)# ...
注意:不能將 grid() 和 pack() 混合使用,否則運行程序會報如下錯誤:_tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack。
在前面的示例中,我們使用 command 參數指定單擊按鈕時要調用的函數。Tkinter 允許你將函數綁定到各種事件,例如單擊按鈕、按鍵或鼠標移動。
讓我們在 Entry Widget 中添加一個事件處理程序,以便在用戶按下 Enter 鍵時向用戶表示歡迎:
# ...def on_enter(event): say_hello()# Bind the on_enter function to the Enter key press evententry.bind("<Return>", on_enter)# ...
現在,在 Entry Widget 中按 Enter 將觸發 say_hello 函數。
前面我們已經了解 Tkinter 的基礎知識,現在讓我們探索其中更高級的概念吧!
Tkinter 可以讓你為應用程序創建菜單。菜單通常包含 File、Edit 和 Help 等菜單項,并且每個菜單項都可以有子菜單和命令。
# ...def exit_app(): root.destroy()# Create a menu barmenu_bar = tk.Menu(root)root.config(menu=menu_bar)# Create a File menufile_menu = tk.Menu(menu_bar, tearoff=0)menu_bar.add_cascade(label="File", menu=file_menu)# Add an "Exit" command to the File menufile_menu.add_command(label="Exit", command=exit_app)# ...
現在,運行程序后將會有一個帶有 Edit 選項的 File 菜單。點擊 Edit 將會關閉應用程序。
框架是用于分組和組織小部件的容器,它們有助于實現更干凈、更有組織的布局。
# ...# Create a frameframe = tk.Frame(root)frame.pack(pady=10)# Create widgets inside the framelabel_in_frame = tk.Label(frame, text="Inside the Frame")button_in_frame = tk.Button(frame, text="Click me!")# Pack widgets inside the framelabel_in_frame.pack()button_in_frame.pack()# ...
在這里,我們創建了一個框架并對其中的小部件進行打包。框架在需要將界面劃分為多個部分時特別有用。
對話框是提示用戶輸入或提供信息的彈出窗口。Tkinter 提供了一種使用 tkinter.messagebox 模塊創建對話框的簡單方法。
# ...from tkinter import messageboxdef show_info(): messagebox.showinfo("Information", "This is an information message.")# ...# Create a button to show the information dialoginfo_button = tk.Button(root, text="Show Info", command=show_info)info_button.pack(pady=10)# ...
點擊 Show Info 按鈕將顯示一個信息對話框:
圖片
Tkinter 支持各種格式的圖像顯示,你可以使用 PhotoImage 類來加載和顯示圖像。
# ...# Load an imageimage = tk.PhotoImage(file="path/to/image.png")# Create a label to display the imageimage_label = tk.Label(root, image=image)image_label.pack(pady=10)# ...
用你的圖片地址替換“path/to/image.png”即可。但實際測試時發現有的 png 圖片可以正常展示,但是有的卻不能,會報如下錯誤:
_tkinter.TclError: couldn't recognize data in image file "images/beutiful_girl.jpg"
網上說 Tkinter 只支持 gif 格式的圖片,要加載 png 或 jpg 格式的圖片應該用 PIL 包的 Image,同時用 ImageTK.PhotoImage 替換 tk.PhotoImage:
from PIL import Image, ImageTkimage = ImageTk.PhotoImage(Image.open("images/beutiful_girl.jpg"))
測試后發現確實可以解決上述報錯問題,如果你也遇到同樣的錯誤,可以嘗試使用這個解決方法。
Tkinter 允許你使用樣式自定義小部件的外觀,你可以為按鈕、標簽和其他小部件定義樣式。
# ...# Create a button with the custom stylestyled_button = tk.Button(root, text="Styled Button", foreground="green", fnotallow=("Arial", 12))styled_button.pack(pady=10)# ...
在本例中,我們為按鈕創建了自定義樣式(綠色文本和指定的字體)。
這個全面的教程涵蓋了 Python 內置 GUI 庫 Tkinter 的基礎和高級功能。從創建一個簡單的“Hello, Tkinter!”應用程序來探索菜單、框架和對話框等高級概念,現在你對構建交互式和用戶友好的應用程序已經有一個扎實的基礎。
記住,實踐是掌握 GUI 開發的關鍵。嘗試不同的小部件、布局和樣式,為您的 Python 應用程序創建完美的界面。Tkinter 的文檔是進一步探索和微調的優秀資源。Happy coding!
本文鏈接:http://www.www897cc.com/showinfo-26-35333-0.htmlPython GUI 新手入門教程:輕松構建圖形用戶界面
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com