最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python?GUI布局工具Tkinter入門之旅

 更新時間:2022年08月01日 14:36:52   作者:周蘿卜  
這篇文章主要為大家介紹了Python?GUI布局工具Tkinter的基礎,Tkinter?作為?Python?的標準庫,是非常流行的?Python?GUI?工具,同時也是非常容易學習的,今天我們就來開啟?Tkinter的入門之旅

圖形用戶界面 (GUI)

圖形用戶界面 (GUI) 只不過是一個桌面應用程序,可幫助我們與計算機進行交互

  • 像文本編輯器這樣的 GUI 應用程序可以創(chuàng)建、讀取、更新和刪除不同類型的文件
  • 數獨、國際象棋和紙牌等應用程序則是游戲版的GUI程序
  • 還有 Google Chrome、Firefox 和 Microsoft Edge 之類的 GUI 應用程序是用來瀏覽 Internet 的

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

今天我們作為 GUI 的入門,將創(chuàng)建一個非常簡單且漂亮的 GUI 應用程序

用于創(chuàng)建GUI的 Python 庫

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

  • Kivy
  • Python QT
  • wxPython
  • Tkinter

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

Tkinter 基礎

下面的圖片顯示了應用程序是如何在 Tkinter 中實際執(zhí)行

我們首先導入 Tkinter 模型,接著,我們創(chuàng)建主窗口,在這個窗口中,我們將要執(zhí)行操作并顯示一切視覺效果,接下來我們添加 Widgets,最后我們進入 Main Event Loop

這里有 2 個重要的關鍵字

  • Widgets
  • Main Event Loop

事件循環(huán)基本上是告訴代碼繼續(xù)顯示窗口,直到我們手動關閉它,是在后臺無限循環(huán)運行的

對于 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

Tkinter Widgets

那么到底什么是 Widgets 呢

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

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

  • Canvas - Canvas 用于在 GUI 中繪制形狀
  • Button – Button 用于在 Tkinter 中放置按鈕
  • Checkbutton – Checkbutton 用于在應用程序中創(chuàng)建復選按鈕
  • Entry - Entry 用于在 GUI 中創(chuàng)建輸入字段
  • Frame – Frame 在 Tkinter 中用作容器
  • Label - Label 用于創(chuàng)建單行 Widgets,如文本、圖像等
  • Menu - Menu 用于在 GUI 中創(chuàng)建菜單

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

Label

標簽用于創(chuàng)建文本和圖像以及所有相關的,而且要注意的是,它只能是單行定義

l1 = Label(window, text="蘿卜大雜燴!", font=("ArialBold", 50))
l1.grid(column=0, row=0)

還有一個函數 geometry,它基本上用于更改窗口大小并根據我們的要求進行設置

l1 = Label(window, text="蘿卜大雜燴!", font=("ArialBold", 50))
window.geometry('350x200')

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

接下來是 button

Button

按鈕與標簽非常相似,我們創(chuàng)建一個變量并使用 Widgets 語法來定義按鈕要表達的內容

window.geometry('350x200')
bt = Button(window, text="Enter")

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

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

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

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

def clicked():
    l1.configure(text="按鈕被點擊了!!")
bt = Button(window, text="Enter", bg="orange", fg="red", command=clicked)

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

我們定義了一個名為 clicked 的函數,可以顯示一條文本消息,我們在按鈕定義中添加一個名為 command 的參數,來調用點擊事件

Entry

它用于在 GUI 中創(chuàng)建輸入字段以接收文本輸入

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 類創(chuàng)建一個文本框,grid 定義我們希望窗口小部件位于何處

同時 clicked 函數接收 Entry 的文本信息

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)

這樣一個下拉菜單就完成了

Checkbutton

復選按鈕是非常常用的組件

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

我們首先創(chuàng)建一個 booleanvar 類型的變量,這是一個 Tkinter 變量

默認情況下,我們將設置狀態(tài)保持為 true,這代表按鈕已經被選中 接下來,我們將 chk_state 傳遞給 checkbutton 類來為我們設置檢查狀態(tài)

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

Scrolled Text

滾動文本組件

scro_txt = scrolledtext.ScrolledText(window, width=40,height=10)
scro_txt.grid(column=0, row=4)

我們指定了窗口的高和寬,否則默認會填充整個 Windiws 窗口

Message Box

消息組件可以方便的彈出提醒消息

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

SpinBox

Spinbox 也是一個常見的組件,有兩個選項卡,存在向上和向下滾動選項卡

pin = Spinbox(window, from_=0, to=100, width=5)

有 3 個參數——from、to 和 width

  • From – 告訴我們范圍的開始和默認值
  • to – 給我們范圍的上限閾值
  • width 基本上是將 widget 的大小設置為5個字符的空格

Geometry

Tkinter 中的所有 Widgets 都會有一些位置信息,這些度量使得我們可以組織 Widgets 及其父框架、窗口等

Tkinter 具有以下三個布局方式

  • pack():- 它在塊中組織 Widgets,這意味著它占據了整個可用寬度,這是在窗口中顯示 Widgets 的標準方法
  • grid():- 它以類似表格的結構組織 Widgets
  • place():- 它將 Widgets 放置在我們想要的特定位置

組織布局

為了在窗口中安排布局,我們將使用 Frame 類

  • Frame -- 在窗口中創(chuàng)建分區(qū),我們可以根據需要使用 pack() 方法的側面參數對齊框架
  • Button -- 在窗口中創(chuàng)建一個按鈕,需要傳遞幾個參數,如文本(按鈕的值)、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()

再來看一個登錄的小栗子

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()

下面我們來了解 binding 函數

binding 函數

每當事件發(fā)生時調用函數就是綁定函數

在下面的示例中,當單擊按鈕時,它會調用一個名為 say_hi 的函數。 函數 say_hi 會創(chuàng)建一個帶有文本 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()

另一種綁定函數的方法是使用事件,事件類似于鼠標移動、鼠標懸停、單擊和滾動等等

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

下面的代碼將使用對于的文本創(chuàng)建一個新標簽

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()

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()

好了,進步的 Tkinter 知識我們都梳理完畢了,下面就完成一個簡單的實戰(zhàn)項目吧

計算器 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入門之旅的詳細內容,更多關于Python GUI布局Tkinter的資料請關注腳本之家其它相關文章!

相關文章

  • Django Docker容器化部署之Django-Docker本地部署

    Django Docker容器化部署之Django-Docker本地部署

    這篇文章主要介紹了Django Docker容器化部署之Django-Docker本地部署,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-10-10
  • Python json模塊使用實例

    Python json模塊使用實例

    這篇文章主要介紹了Python json模塊使用實例,本文給出多個使用代碼實例,需要的朋友可以參考下
    2015-04-04
  • Python?pandas索引的設置和修改方法

    Python?pandas索引的設置和修改方法

    索引的作用相當于圖書的目錄,可以根據目錄中的頁碼快速找到所需的內容,下面這篇文章主要給大家介紹了關于Python?pandas索引的設置和修改的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-06-06
  • Python使用execjs模塊運行JavaScript代碼

    Python使用execjs模塊運行JavaScript代碼

    在編程中,Python和JavaScript是兩種使用廣泛的編程語言,本文將深入探索如何通過execjs模塊在Python中運行JavaScript代碼,有需要的可以參考一下
    2025-03-03
  • python爬取本站電子書信息并入庫的實現代碼

    python爬取本站電子書信息并入庫的實現代碼

    這篇文章主要介紹了python爬取本站電子書信息并入庫的實現代碼,需要的朋友可以參考下
    2020-01-01
  • Python教程之成員和身份運算符的用法詳解

    Python教程之成員和身份運算符的用法詳解

    身份運算符是python用來判斷的兩個對象的存儲單元是否相同的一種運算符號。Python的成員運算符是“是否包含運算符”,主要應用在字符串或者集合中。本文將通過示例聊聊二者的使用,需要的可以參考一下
    2022-09-09
  • win10系統(tǒng)下Anaconda3安裝配置方法圖文教程

    win10系統(tǒng)下Anaconda3安裝配置方法圖文教程

    這篇文章主要為大家詳細介紹了win10系統(tǒng)下Anaconda3安裝配置方法圖文教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • 如何使用Python一鍵修改上萬個文件名

    如何使用Python一鍵修改上萬個文件名

    各位有沒有遇到過需要批量整理多層文件夾結構里各種類型(docx、excel、ppt)的文件材料的時候,下面這篇文章主要給大家介紹了關于如何使用Python一鍵修改上萬個文件名的相關資料,需要的朋友可以參考下
    2022-05-05
  • Python PCA降維的兩種實現方法

    Python PCA降維的兩種實現方法

    大家好,本篇文章主要講的是Python PCA降維的兩種實現方法,感興趣的的同學趕快來看一看吧,對你有幫助的話記得收藏一下
    2022-01-01
  • Numpy截取指定范圍內的數據方法

    Numpy截取指定范圍內的數據方法

    今天小編就為大家分享一篇Numpy截取指定范圍內的數據方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11

最新評論

武定县| 洛川县| 岳池县| 兰坪| 安仁县| 神农架林区| 韩城市| 塔城市| 英吉沙县| 伊川县| 泰兴市| 西城区| 肃北| 岚皋县| 安康市| 筠连县| 长垣县| 漠河县| 石首市| 西畴县| 郓城县| 延庆县| 威远县| 双鸭山市| 西吉县| 射洪县| 栖霞市| 遂平县| 友谊县| 普兰县| 陆丰市| 郸城县| 师宗县| 高安市| 沿河| 牙克石市| 江门市| 玉林市| 手游| 四子王旗| 邳州市|