目錄
圖形使用者介面(GUI)
用於創建GUI的Python 庫
Tkinter 基礎
Tkinter Widgets
Entry
Combobox
Checkbutton
Radio Button
Scrolled Text
Message Box
SpinBox
Geometry
组织布局
binding 函数
Images 和 Icons
计算器 APP
首頁 後端開發 Python教學 Python GUI佈局工具Tkinter使用方法是什麼

Python GUI佈局工具Tkinter使用方法是什麼

May 09, 2023 pm 02:16 PM
python gui tkinter

    圖形使用者介面(GUI)

    圖形使用者介面(GUI) 只不過是一個桌面應用程序,可幫助我們與電腦進行互動

    • 像文字編輯器這樣的GUI 應用程式可以建立、讀取、更新和刪除不同類型的檔案

    • 數獨、國際象棋和紙牌等應用程式則是遊戲版的GUI程式

    • 還有Google Chrome、Firefox 和Microsoft Edge 之類的GUI 應用程式是用來瀏覽Internet 的

    #這些都是我們日常在電腦上使用的一些不同類型的GUI 應用程序,其實我們透過Tkinter 也是可以建立簡單的類似應用程式的

    今天我們作為GUI 的入門,將創建一個非常簡單且漂亮的GUI 應用程式

    用於創建GUI的Python 庫

    Python 有大量的第三方類別庫,對於GUI 庫,主要有以下幾種:

    • Kivy

    • Python QT

    • wxPython

    • Tkinter

    其中,Tkinter 是許多學習者和開發者的首選,因為它簡單易用而且隨Python 安裝自帶

    Tkinter 基礎

    下面的圖片顯示了應用程式是如何在Tkinter 中實際執行

    Python GUI佈局工具Tkinter使用方法是什麼

    #我們首先導入Tkinter 模型,接著,我們創建主窗口,在這個窗口中,我們將要執行操作並顯示一切視覺效果,接下來我們加入Widgets,最後我們進入Main Event Loop

    這裡有2 個重要的關鍵字

    • Widgets

    • Main Event Loop

    事件循環基本上是告訴程式碼繼續顯示窗口,直到我們手動關閉它,是在後台無限循環運行的

    對於Widgets 我們後面單獨學習

    下面一個程式碼例子,來深入理解下

    import tkinter
    window = tkinter.Tk()
    # to rename the title of the window window.title("GUI")
    # pack is used to show the object in the window
    label = tkinter.Label(window, text = "Hello World!").pack()
    window.mainloop()
    登入後複製

    我們匯入Tkinter 套件並定義一個窗口,接著我們可以修改一個視窗標題,每當打開應用程式時,該標題都會顯示在標題選項卡上

    最後,我們還定義了一個標籤,標籤只不過是需要在視窗上顯示的輸出,在例子中是hello world

    Python GUI佈局工具Tkinter使用方法是什麼

    Tkinter Widgets

    那麼到底什麼是Widgets 呢

    Widgets 類似HTML 中的元素,我們可以在Tkinter 中找到針對不同類型元素的不同類型的Widgets

    讓我們看看Tkinter 中所有這些Widgets 的簡要介紹

    Python GUI佈局工具Tkinter使用方法是什麼

    • Canvas - Canvas 使用於在GUI 中繪製形狀

    • Button – Button 用於在Tkinter 中放置按鈕

    • ##Checkbutton – Checkbutton 用於在應用程式中建立複選按鈕

    • Entry - Entry 用於在GUI 中建立輸入欄位

    • Frame – Frame 在Tkinter 中用作容器

    • Label - Label 用於建立單行Widgets,如文字、圖片等

    • Menu - Menu 用於在GUI 中建立選單

    下面讓我們逐一看一下每個Widgets 的用法

    Label

    標籤用於創建文字和圖像以及所有相關的,而且要注意的是,它只能是單行定義

    l1 = Label(window, text="萝卜大杂烩!", font=("ArialBold", 50))
    l1.grid(column=0, row=0)
    登入後複製

    Python GUI佈局工具Tkinter使用方法是什麼

    還有一個函數geometry,它基本上用於更改視窗大小並根據我們的要求進行設定

    l1 = Label(window, text="萝卜大杂烩!", font=("ArialBold", 50))
    window.geometry('350x200')
    登入後複製

    在這種情況下,我們將其設置為寬350 像素和高200 像素

    接下來是button

    #Button

    按鈕與標籤非常相似,我們建立一個變數並使用Widgets 語法來定義按鈕要表達的內容

    window.geometry('350x200')
    bt = Button(window, text="Enter")
    登入後複製

    Python GUI佈局工具Tkinter使用方法是什麼

    #我們也可以更改按鈕或任何其他Widgets 的前景顏色,使用程式碼中所示的參數FG。同樣,也可以使用BG 屬性更改背景顏色

    bt = Button(window, text="Enter", bg="orange", fg="red")
    bt.grid(column=1, row=0)
    登入後複製

    Python GUI佈局工具Tkinter使用方法是什麼

    我們的前景是定義為紅色的文本,背景為橙色

    #下面來看一下點擊按鈕的操作

    def clicked():
        l1.configure(text="按钮被点击了!!")
    bt = Button(window, text="Enter", bg="orange", fg="red", command=clicked)
    登入後複製

    這個我們稱之為點擊事件,我們需要編寫有關單擊按鈕或觸發單擊事件時應該發生什麼的功能

    #我們定義了一個名為clicked 的函數,可以顯示一則文字訊息,我們在按鈕定義中新增一個名為command 的參數,來呼叫點擊事件

    Python GUI佈局工具Tkinter使用方法是什麼

    Entry

    它用于在 GUI 中创建输入字段以接收文本输入

    txt = Entry(window, width=10)
    txt.grid(column=1, row=0)
    def clicked():
        res = "Welcome to " + txt.get()
        l1.configure(text=res)
    bt = Button(window, text="Enter", bg="orange", fg="red", command=clicked)
    登入後複製

    在这里,我们使用 Tkinter Entry 类创建一个文本框,grid 定义我们希望窗口小部件位于何处

    同时 clicked 函数接收 Entry 的文本信息

    Python GUI佈局工具Tkinter使用方法是什麼

    Combobox

    这是一个带有某些选项的下拉菜单

    from tkinter.ttk import *
    combo = Combobox(window)
    combo['values']= (1, 2, 3, 4, 5, "Text")
    combo.current(3)
    combo.grid(column=0, row=0)
    登入後複製

    Python GUI佈局工具Tkinter使用方法是什麼

    这样一个下拉菜单就完成了

    Checkbutton

    复选按钮是非常常用的组件

    chk_state = BooleanVar()
    chk_state.set (True)
    chk = Checkbutton(window, text="Select", var=chk_state)
    chk.grid(column=4, row=0)
    登入後複製

    我们首先创建一个 booleanvar 类型的变量,这是一个 Tkinter 变量

    默认情况下,我们将设置状态保持为 true,这代表按钮已经被选中 接下来,我们将 chk_state 传递给 checkbutton 类来为我们设置检查状态

    Python GUI佈局工具Tkinter使用方法是什麼

    Radio Button

    单选按钮也是非常常用的

    rad1 = Radiobutton(window, text=Python', value=1)
    rad2 = Radiobutton(window, text=Java', value=2)
    rad3 = Radiobutton(window, text=Scala', value=3)
    rad1.grid(column=0, row=0)
    rad2.grid(column=1, row=0)
    rad3.grid(column=2, row=0)
    登入後複製

    在这里,我们使用了不同的参数值,1,2和3,如果它们相同,则会导致冲突并出现错误

    它们的文本数据是可以相同,在这里,我们使用了 Python、Java 和 Scala

    Python GUI佈局工具Tkinter使用方法是什麼

    Scrolled Text

    滚动文本组件

    scro_txt = scrolledtext.ScrolledText(window, width=40,height=10)
    scro_txt.grid(column=0, row=4)
    登入後複製

    我们指定了窗口的高和宽,否则默认会填充整个 Windiws 窗口

    Python GUI佈局工具Tkinter使用方法是什麼

    Message Box

    消息组件可以方便的弹出提醒消息

    def clicked():
        messagebox.showinfo('Message title', 'Message content')
    btn = Button(window,text=‘ENTER', command=clicked)
    登入後複製

    Python GUI佈局工具Tkinter使用方法是什麼

    SpinBox

    Spinbox 也是一个常见的组件,有两个选项卡,存在向上和向下滚动选项卡

    pin = Spinbox(window, from_=0, to=100, width=5)
    登入後複製

    有 3 个参数——from、to 和 width

    • From – 告诉我们范围的开始和默认值

    • to – 给我们范围的上限阈值

    • width 基本上是将 widget 的大小设置为5个字符的空格

    Python GUI佈局工具Tkinter使用方法是什麼

    Geometry

    Tkinter 中的所有 Widgets 都会有一些位置信息,这些度量使得我们可以组织 Widgets 及其父框架、窗口等

    Tkinter 具有以下三个布局方式

    • pack():- 它在块中组织 Widgets,这意味着它占据了整个可用宽度,这是在窗口中显示 Widgets 的标准方法

    • grid():- 它以类似表格的结构组织 Widgets

    • place():- 它将 Widgets 放置在我们想要的特定位置

    组织布局

    为了在窗口中安排布局,我们将使用 Frame 类

    • Frame -- 在窗口中创建分区,我们可以根据需要使用 pack() 方法的侧面参数对齐框架

    • Button -- 在窗口中创建一个按钮,需要传递几个参数,如文本(按钮的值)、fg(文本的颜色)、bg(背景颜色)

    在下面的代码中,我们使用 window、top_frame、bottom_frame 来布局

    import tkinter
    window = tkinter.Tk()
    window.title("GUI")
    # creating 2 frames TOP and BOTTOM
    top_frame = tkinter.Frame(window).pack()
    bottom_frame = tkinter.Frame(window).pack(side = "bottom")
    # now, create some widgets in the top_frame and bottom_frame
    btn1 = tkinter.Button(top_frame, text = "Button1", fg = "red").pack()# 'fg - foreground' is used to color the contents
    btn2 = tkinter.Button(top_frame, text = "Button2", fg = "green").pack()# 'text' is used to write the text on the Button
    btn3 = tkinter.Button(bottom_frame, text = "Button2", fg = "purple").pack(side = "left")# 'side' is used to align the widgets
    btn4 = tkinter.Button(bottom_frame, text = "Button2", fg = "orange").pack(side = "left")
    window.mainloop()
    登入後複製

    Python GUI佈局工具Tkinter使用方法是什麼

    再来看一个登录的小栗子

    import tkinter
    window = tkinter.Tk()
    window.title("GUI")
    # creating 2 text labels and input labels
    tkinter.Label(window, text = "Username").grid(row = 0) # this is placed in 0 0
    # 'Entry' is used to display the input-field
    tkinter.Entry(window).grid(row = 0, column = 1) # this is placed in 0 1
    tkinter.Label(window, text = "Password").grid(row = 1) # this is placed in 1 0
    tkinter.Entry(window).grid(row = 1, column = 1) # this is placed in 1 1
    # 'Checkbutton' is used to create the check buttons
    tkinter.Checkbutton(window, text = "Keep Me Logged In").grid(columnspan = 2) # 'columnspan' tells to take the width of 2 columns
    # you can also use 'rowspan' in the similar manner
    window.mainloop()
    登入後複製

    Python GUI佈局工具Tkinter使用方法是什麼

    下面我们来了解 binding 函数

    binding 函数

    每当事件发生时调用函数就是绑定函数

    在下面的示例中,当单击按钮时,它会调用一个名为 say_hi 的函数。 函数 say_hi 会创建一个带有文本 Hi 的新标签

    import tkinter
    window = tkinter.Tk()
    window.title("GUI")
    # creating a function called say_hi()
    def say_hi():
        tkinter.Label(window, text = "Hi").pack()
    tkinter.Button(window, text = "Click Me!", command = say_hi).pack() # 'command' is executed when you click the button
    # in this above case we're calling the function 'say_hi'.
    window.mainloop()
    登入後複製

    Python GUI佈局工具Tkinter使用方法是什麼

    另一种绑定函数的方法是使用事件,事件类似于鼠标移动、鼠标悬停、单击和滚动等等

    import tkinter
    window = tkinter.Tk()
    window.title("GUI")
    # creating a function with an arguments 'event'
    def say_hi(event): # you can rename 'event' to anything you want
        tkinter.Label(window, text = "Hi").pack()
    btn = tkinter.Button(window, text = "Click Me!")
    btn.bind("Button-1", say_hi) # 'bind' takes 2 parameters 1st is 'event' 2nd is 'function'
    btn.pack()
    window.mainloop()
    登入後複製

    单击事件有 3 种不同的类型,分别是 leftClick、middleClick 和 rightClick

    下面的代码将使用对于的文本创建一个新标签

    import tkinter
    window = tkinter.Tk()
    window.title("GUI")
    #creating 3 different functions for 3 events
    def left_click(event):
        tkinter.Label(window, text = "Left Click!").pack()
    def middle_click(event):
        tkinter.Label(window, text = "Middle Click!").pack()
    def right_click(event):
        tkinter.Label(window, text = "Right Click!").pack()
    window.bind("Button-1", left_click)
    window.bind("Button-2", middle_click)
    window.bind("Button-3", right_click)
    window.mainloop()
    登入後複製

    Python GUI佈局工具Tkinter使用方法是什麼

    Images 和 Icons

    我们可以使用 PhotoImage 方法添加图像和图标

    import tkinter
    window = tkinter.Tk()
    window.title("GUI")
    # taking image from the directory and storing the source in a variable
    icon = tkinter.PhotoImage(file = "4.PNG")
    # displaying the picture using a 'Label' by passing the 'picture' variriable to 'image' parameter
    label = tkinter.Label(window, image = icon)
    label.pack()
    window.mainloop()
    登入後複製

    Python GUI佈局工具Tkinter使用方法是什麼

    好了,进步的 Tkinter 知识我们都梳理完毕了,下面就完成一个简单的实战项目吧

    计算器 APP

    首先初始化页面

    window = Tk()
    window.geometry("350x380")
    window.resizable(0, 0)  # this prevents from resizing the window
    window.title("小小计算器")
    登入後複製

    接下来定义输入数字框

    input_text = StringVar()
    input_frame = Frame(window, width=312, height=50, bd=0, highlightbackground="black", highlightcolor="black",
                        highlightthickness=1)
    input_frame.pack(side=TOP)
    input_field = Entry(input_frame, font=('arial', 18, 'bold'), textvariable=input_text, width=50, bg="#eee", bd=0,
                        justify=RIGHT)
    input_field.grid(row=0, column=0)
    input_field.pack(ipady=10)
    登入後複製

    然后定义按钮方法,我们以清除按钮和除法按钮为例

    clear = Button(btns_frame, text="C", fg="black", width=32, height=3, bd=0, bg="#eee", cursor="hand2",
                   command=lambda: btn_clear()).grid(row=0, column=0, columnspan=3, padx=1, pady=1)
    divide = Button(btns_frame, text="/", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2",
                    command=lambda: btn_click("/")).grid(row=0, column=3, padx=1, pady=1)
    登入後複製

    最后就是计算equal逻辑

    equals = Button(btns_frame, text="=", fg="black", width=10, height=3, bd=0, bg="#eee", cursor="hand2",
                   command=lambda: btn_equal()).grid(row=4, column=3, padx=1, pady=1)
    def btn_equal():
       global expression
       result = str(eval(expression)) 
       input_text.set(result)
       expression = ""
    登入後複製

    以上是Python GUI佈局工具Tkinter使用方法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    本網站聲明
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

    熱AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智慧驅動的應用程序,用於創建逼真的裸體照片

    AI Clothes Remover

    AI Clothes Remover

    用於從照片中去除衣服的線上人工智慧工具。

    Undress AI Tool

    Undress AI Tool

    免費脫衣圖片

    Clothoff.io

    Clothoff.io

    AI脫衣器

    AI Hentai Generator

    AI Hentai Generator

    免費產生 AI 無盡。

    熱門文章

    R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
    3 週前 By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.最佳圖形設置
    3 週前 By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.如果您聽不到任何人,如何修復音頻
    3 週前 By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25:如何解鎖Myrise中的所有內容
    4 週前 By 尊渡假赌尊渡假赌尊渡假赌

    熱工具

    記事本++7.3.1

    記事本++7.3.1

    好用且免費的程式碼編輯器

    SublimeText3漢化版

    SublimeText3漢化版

    中文版,非常好用

    禪工作室 13.0.1

    禪工作室 13.0.1

    強大的PHP整合開發環境

    Dreamweaver CS6

    Dreamweaver CS6

    視覺化網頁開發工具

    SublimeText3 Mac版

    SublimeText3 Mac版

    神級程式碼編輯軟體(SublimeText3)

    mysql 是否要付費 mysql 是否要付費 Apr 08, 2025 pm 05:36 PM

    MySQL 有免費的社區版和收費的企業版。社區版可免費使用和修改,但支持有限,適合穩定性要求不高、技術能力強的應用。企業版提供全面商業支持,適合需要穩定可靠、高性能數據庫且願意為支持買單的應用。選擇版本時考慮的因素包括應用關鍵性、預算和技術技能。沒有完美的選項,只有最合適的方案,需根據具體情況謹慎選擇。

    mysql安裝後怎麼使用 mysql安裝後怎麼使用 Apr 08, 2025 am 11:48 AM

    文章介紹了MySQL數據庫的上手操作。首先,需安裝MySQL客戶端,如MySQLWorkbench或命令行客戶端。 1.使用mysql-uroot-p命令連接服務器,並使用root賬戶密碼登錄;2.使用CREATEDATABASE創建數據庫,USE選擇數據庫;3.使用CREATETABLE創建表,定義字段及數據類型;4.使用INSERTINTO插入數據,SELECT查詢數據,UPDATE更新數據,DELETE刪除數據。熟練掌握這些步驟,並學習處理常見問題和優化數據庫性能,才能高效使用MySQL。

    如何針對高負載應用程序優化 MySQL 性能? 如何針對高負載應用程序優化 MySQL 性能? Apr 08, 2025 pm 06:03 PM

    MySQL數據庫性能優化指南在資源密集型應用中,MySQL數據庫扮演著至關重要的角色,負責管理海量事務。然而,隨著應用規模的擴大,數據庫性能瓶頸往往成為製約因素。本文將探討一系列行之有效的MySQL性能優化策略,確保您的應用在高負載下依然保持高效響應。我們將結合實際案例,深入講解索引、查詢優化、數據庫設計以及緩存等關鍵技術。 1.數據庫架構設計優化合理的數據庫架構是MySQL性能優化的基石。以下是一些核心原則:選擇合適的數據類型選擇最小的、符合需求的數據類型,既能節省存儲空間,又能提升數據處理速度

    mysql安裝後怎麼優化數據庫性能 mysql安裝後怎麼優化數據庫性能 Apr 08, 2025 am 11:36 AM

    MySQL性能優化需從安裝配置、索引及查詢優化、監控與調優三個方面入手。 1.安裝後需根據服務器配置調整my.cnf文件,例如innodb_buffer_pool_size參數,並關閉query_cache_size;2.創建合適的索引,避免索引過多,並優化查詢語句,例如使用EXPLAIN命令分析執行計劃;3.利用MySQL自帶監控工具(SHOWPROCESSLIST,SHOWSTATUS)監控數據庫運行狀況,定期備份和整理數據庫。通過這些步驟,持續優化,才能提升MySQL數據庫性能。

    mysql 需要互聯網嗎 mysql 需要互聯網嗎 Apr 08, 2025 pm 02:18 PM

    MySQL 可在無需網絡連接的情況下運行,進行基本的數據存儲和管理。但是,對於與其他系統交互、遠程訪問或使用高級功能(如復制和集群)的情況,則需要網絡連接。此外,安全措施(如防火牆)、性能優化(選擇合適的網絡連接)和數據備份對於連接到互聯網的 MySQL 數據庫至關重要。

    Navicat查看MongoDB數據庫密碼的方法 Navicat查看MongoDB數據庫密碼的方法 Apr 08, 2025 pm 09:39 PM

    直接通過 Navicat 查看 MongoDB 密碼是不可能的,因為它以哈希值形式存儲。取回丟失密碼的方法:1. 重置密碼;2. 檢查配置文件(可能包含哈希值);3. 檢查代碼(可能硬編碼密碼)。

    HadiDB:Python 中的輕量級、可水平擴展的數據庫 HadiDB:Python 中的輕量級、可水平擴展的數據庫 Apr 08, 2025 pm 06:12 PM

    HadiDB:輕量級、高水平可擴展的Python數據庫HadiDB(hadidb)是一個用Python編寫的輕量級數據庫,具備高度水平的可擴展性。安裝HadiDB使用pip安裝:pipinstallhadidb用戶管理創建用戶:createuser()方法創建一個新用戶。 authentication()方法驗證用戶身份。 fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

    mysql workbench 可以連接到 mariadb 嗎 mysql workbench 可以連接到 mariadb 嗎 Apr 08, 2025 pm 02:33 PM

    MySQL Workbench 可以連接 MariaDB,前提是配置正確。首先選擇 "MariaDB" 作為連接器類型。在連接配置中,正確設置 HOST、PORT、USER、PASSWORD 和 DATABASE。測試連接時,檢查 MariaDB 服務是否啟動,用戶名和密碼是否正確,端口號是否正確,防火牆是否允許連接,以及數據庫是否存在。高級用法中,使用連接池技術優化性能。常見錯誤包括權限不足、網絡連接問題等,調試錯誤時仔細分析錯誤信息和使用調試工具。優化網絡配置可以提升性能

    See all articles