偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

萬(wàn)字長(zhǎng)文,從 0 到 1 使用 Tkinter 構(gòu)建 GUI 界面軟件

開(kāi)發(fā)
本文是關(guān)于Python Tkinter庫(kù)入門(mén)指南的全部?jī)?nèi)容。希望能夠幫助您快速掌握Tkinter庫(kù)的基礎(chǔ)知識(shí),并能夠運(yùn)用所學(xué)知識(shí)來(lái)創(chuàng)建自己的圖形用戶界面應(yīng)用程序。?

Tkinter(也叫 Tk 接口)是 Tk 圖形用戶界面工具包標(biāo)準(zhǔn)的 Python 接口。Tk 是一個(gè)輕量級(jí)的跨平臺(tái)圖形用戶界面 (GUI)開(kāi)發(fā)工具。Tk 和 Tkinter 可以運(yùn)行在大多數(shù) 的 Unix 平臺(tái)、Windows、和 Macintosh 系統(tǒng)。由于Tkinter是Python自帶的標(biāo)準(zhǔn)庫(kù),我們想要使用它的時(shí)候,只需直接導(dǎo)入即可。

一、為什么使用Tkinter庫(kù)

Tkinter庫(kù)具有以下優(yōu)點(diǎn):

  • 它是Python的標(biāo)準(zhǔn)GUI庫(kù),無(wú)需安裝第三方庫(kù)即可使用。
  • 它提供了豐富的組件和布局管理器,能夠滿足大多數(shù)應(yīng)用程序的需求。
  • 它具有良好的跨平臺(tái)性,能夠在多種操作系統(tǒng)上運(yùn)行。

二、如何使用

在項(xiàng)目中使用Tkinter庫(kù)時(shí),只需在代碼開(kāi)頭導(dǎo)入Tkinter模塊即可。

1import tkinter as tk

打開(kāi)你的IDE或虛擬環(huán)境,執(zhí)行下面命令,會(huì)彈出Tkinter構(gòu)建的小示例。

1python -m tkinter

三、Tkinter基礎(chǔ)

1. 窗口和組件

在Tkinter中,窗口和組件都是對(duì)象。曾做過(guò)VC或者Delphi開(kāi)發(fā)的是不是很熟悉?;旧暇褪荈orm、Component。各種窗口、組件的屬性、事件、生命周期構(gòu)成了整個(gè)軟件的運(yùn)行。

我們創(chuàng)建通過(guò)tk.Tk()創(chuàng)建一個(gè)Form。設(shè)置窗口寬(500)、高(300),設(shè)置Form的title并啟動(dòng)。

1import tkinter as tk
 2
 3# 創(chuàng)建Form
 4window = tk.Tk()
 5
 6# 設(shè)置Form屬性
 7window.title("用戶登錄")
 8window.maxsize(500, 300)
 9window.geometry('500x300')
10
11# 創(chuàng)建標(biāo)簽組件
12label = tk.Label(window, text="Hello, Tkinter!")
13label.pack()
14
15# 創(chuàng)建按鈕組件
16button = tk.Button(window, text="Click me!")
17button.pack()
18# 運(yùn)行
19window.mainloop()

上面的代碼中,我們首先導(dǎo)入了tkinter模塊,并創(chuàng)建了一個(gè)Form對(duì)象window。然后,我們創(chuàng)建了一個(gè)標(biāo)簽組件label和一個(gè)按鈕組件button,并使用pack()方法將它們添加到窗口中。最后,我們調(diào)用窗口對(duì)象的mainloop()方法來(lái)運(yùn)行主循環(huán)。

2. 布局管理

雖然上面能夠正常運(yùn)行,但看起來(lái)很丑,所以我們也做好組件的布局。在Tkinter中,布局管理器負(fù)責(zé)管理組件的位置和大小。目前,Tkinter提供了三種布局管理器:pack、grid和place。

  • pack布局管理器:按照添加順序?qū)⒔M件放置到窗口中。
  • grid布局管理器:將窗口劃分為網(wǎng)格,并將組件放置到指定的網(wǎng)格中。
  • place布局管理器:允許開(kāi)發(fā)者精確地控制組件的位置和大小。

下面是grid基于網(wǎng)格布局的登錄窗口:

1import tkinter as tk
 2
 3
 4def login():
 5    username = username_entry.get()
 6    password = password_entry.get()
 7    print(username, password)
 8
 9
10window = tk.Tk()
11window.title("用戶登錄")
12window.maxsize(300, 200)
13window.geometry('300x200')
14
15tk.Label(window, text="用戶名:").grid(padx=30, pady=30, row=2, column=0)
16username_entry = tk.Entry(window)
17username_entry.grid(row=2, column=1)
18
19# 密碼輸入
20tk.Label(window, text="密碼:").grid(row=4, column=0)
21password_entry = tk.Entry(window, show="*")
22password_entry.grid(row=4, column=1)
23
24# 登錄按鈕
25login_btn = tk.Button(window, text="登錄", command=login)
26login_btn.grid(pady=20, row=8, columnspan=3)
27
28window.mainloop()

上面代碼定義了一個(gè)300x200的Form。添加5個(gè)組件:2個(gè)Label,2個(gè)Input框,和一個(gè)按鈕Button。每個(gè)組件在不同網(wǎng)格中。button按鈕的事件Event是login。

3. 基礎(chǔ)組件說(shuō)明

以下是 Tkinter 主要組件的列表、簡(jiǎn)單示例、常用屬性及事件說(shuō)明:

(1) Label(標(biāo)簽)

用途: 顯示文本或圖像  示例: 獲取、失去焦點(diǎn)、綁定事件、顏色變換

1# 鼠標(biāo)進(jìn)入時(shí)改變背景
 2def on_enter(event):
 3    label.config(bg="lightgreen", fg="black")
 4
 5# 鼠標(biāo)離開(kāi)時(shí)恢復(fù)顏色
 6def on_leave(event):
 7    label.config(bg="white", fg="gray")  
 8
 9# 鼠標(biāo)點(diǎn)擊事件
10def on_press(event):
11    label.config(bg="lightgreen", fg="black")
12    print('press',event.x,event.y)
13
14window = tk.Tk()
15label = tk.Label(window, text="Hover over me!", bg="white", fg="gray", padx=20, pady=10)
16label.pack(pady=20)
17
18# 綁定事件
19label.bind("<Enter>", on_enter)
20label.bind("<Leave>", on_leave
21label.bind("<Button-1>", on_press)

常用屬性:

  • text: 顯示的文字
  • bg/background: 背景色
  • fg/foreground: 文字顏色
  • font: 字體
  • image: 顯示圖像(需配合 PhotoImage 使用)

事件:

  • Button-1: 鼠標(biāo)左鍵點(diǎn)擊
  • Enter/Leave: 鼠標(biāo)進(jìn)入/離開(kāi)區(qū)域

(2) Button(按鈕)

用途: 觸發(fā)命令  示例: 按鈕狀態(tài)切換,并設(shè)置可用、不可用

1# 定義一個(gè)bool型變量
 2is_enabled = tk.BooleanVar(value=True)
 3
 4
 5# 切換狀態(tài)
 6def toggle_state():
 7    is_enabled.set(not is_enabled.get())  # 切換狀態(tài)
 8
 9
10button = tk.Button(
11    window,
12    text="Toggle State",
13    state=tk.NORMAL if is_enabled.get() else tk.DISABLED,
14    command=toggle_state
15)
16button.pack()
17
18
19# 綁定變量到按鈕狀態(tài)
20def update_state(event):
21    button.config(state=tk.NORMAL if is_enabled.get() else tk.DISABLED)
22
23
24update_btn = tk.Button(window, text="Update State")
25update_btn.bind("<Button-1>", update_state)
26update_btn.pack()

常用屬性:

  • text: 按鈕文字
  • command: 點(diǎn)擊時(shí)觸發(fā)的函數(shù)
  • state: 狀態(tài)(normal/disabled)

事件:

  • Button-1: 鼠標(biāo)左鍵點(diǎn)擊(可通過(guò) bind 綁定)

(3) Entry(輸入框)

用途: 單行文本輸入,綁定變量輸出, 回車、失去、獲取焦點(diǎn)事件示例:

1# 創(chuàng)建一個(gè) StringVar 變量并綁定到輸入框
 2# 創(chuàng)建一個(gè) StringVar 變量并綁定到輸入框
 3text_var = tk.StringVar()
 4
 5
 6def update_label():
 7    label.config(text=f"輸入內(nèi)容:{text_var.get()}")
 8
 9
10def on_return(event):
11    print("用戶按下了回車鍵,輸入內(nèi)容:", username.get())
12
13
14def on_focus_in(event):
15    password.config(bg="lightyellow")  # 獲得焦點(diǎn)時(shí)背景變亮黃色
16
17
18def on_focus_out(event):
19    password.config(bg="white")  # 失去焦點(diǎn)時(shí)恢復(fù)白色
20    print(password.get())
21
22
23username = tk.Entry(window, textvariable=text_var)
24username.pack(pady=10)
25
26# 實(shí)時(shí)顯示輸入框內(nèi)容的變化
27label = tk.Label(window, text="賬號(hào)輸入:")
28label.pack()
29
30label1 = tk.Label(window, text="密碼輸入:")
31label1.pack()
32
33password = tk.Entry(window, show='*')
34password.pack(pady=10)
35
36# 監(jiān)聽(tīng)變量變化(需手動(dòng)觸發(fā))
37username.bind("<KeyRelease>", lambda e: update_label())
38# 綁定回車事件
39username.bind("<Return>", on_return)
40
41# 獲取或失去焦點(diǎn)
42password.bind("<FocusIn>", on_focus_in)
43password.bind("<FocusOut>", on_focus_out)

常用屬性:

  • textvariable: 綁定變量(如 StringVar)
  • show: 輸入掩碼(如密碼顯示為 *)

事件:

  • Return: 按下回車鍵
  • FocusIn/FocusOut: 焦點(diǎn)進(jìn)入/離開(kāi)

(4) Text(多行文本框)

用途: 多行文本編輯  示例: 插入多行文本,并為key=a的打tag

1def on_key_press(event):
 2    # 獲取當(dāng)前插入點(diǎn)的位置
 3    current_index = text.index(tk.INSERT)
 4
 5    # 獲取按下的鍵
 6    key = event.char
 7
 8    # 如果按下了特定的鍵(例如 'a'),添加一個(gè)標(biāo)記
 9    if key == 'a':
10        # 定義一個(gè)標(biāo)記名稱
11        tag_name = "highlight"
12
13        # 添加標(biāo)記到當(dāng)前字符位置,-1c為向前移動(dòng)一個(gè)字符
14        text.tag_add(tag_name, current_index + "-1c", current_index)
15
16        # 配置標(biāo)記的樣式(例如背景顏色)
17        text.tag_config(tag_name, background="yellow", foreground="red")
18
19    # 打印按鍵信息
20    print(f"Key pressed: {key} at position {current_index}")
21
22
23# 創(chuàng)建 Text 組件
24text = tk.Text(window, width=40, height=10)
25text.pack(padx=10, pady=10)
26# 插入光標(biāo)位置
27text.insert(tk.INSERT, "Hello World")
28# 結(jié)尾處插入
29text.insert(tk.END, "Goodbye World")
30# 綁定 <KeyPress> 事件
31text.bind("<KeyPress>", on_key_press)

常用屬性:

  • height: 高度(行數(shù))
  • width: 寬度(字符數(shù))

事件:

  • 按鍵事件
  • 支持自定義標(biāo)記和綁定事件

(5) Frame(框架)

用途: 容器組件,用于分組其他組件  示例: 設(shè)置容器及邊緣線和邊框格式

1# 邊緣寬度、邊框格式
2frame = tk.Frame(window, borderwidth=2, relief="groove")
3frame.pack()
4# 按鈕在frame容器內(nèi)部,可做部署使用
5tk.Button(frame, text="Inside Frame").pack()

(6) Checkbutton(復(fù)選框)

用途: 多選項(xiàng)選擇  示例: 選中復(fù)選框,然后點(diǎn)擊按鈕

1# 定義一個(gè) Tkinter 變量
 2var = tk.StringVar()
 3
 4# 設(shè)置 Checkbutton 的 onvalue 和 offvalue
 5checkbutton = tk.Checkbutton(
 6    window,
 7    text="Select Me",
 8    variable=var,  # 綁定到變量 var
 9    notallow="ON",  # 選中時(shí)的值
10    offvalue="OFF"# 未選中時(shí)的值
11)
12checkbutton.pack(pady=10)
13
14# 添加一個(gè)按鈕來(lái)顯示當(dāng)前值
15def show_value():
16    print(f"Checkbutton value: {var.get()}")
17
18
19button = tk.Button(window, text="Show Value", command=show_value)
20button.pack(pady=10)
21
22# 設(shè)置 Checkbutton 初始狀態(tài)為未選中
23var.set("OFF")  # 初始化為 offvalue 的值

屬性:

  • variable: 綁定變量(如 IntVar)
  • onvalue/offvalue: 選中/未選中的值

(7) Radiobutton(單選按鈕)

用途: 單選選項(xiàng)  示例: 點(diǎn)擊單選按鈕,設(shè)置變量var值

1var = tk.StringVar()
2tk.Radiobutton(root, text="Option 1", variable=var, value="1").pack()
3tk.Radiobutton(root, text="Option 2", variable=var, value="2").pack()

(8) Listbox(列表框)

用途: 顯示列表項(xiàng)示例: 獲取選中內(nèi)容、插入、刪除列表item

1# 創(chuàng)建 Listbox 組件
 2listbox = tk.Listbox(window)
 3listbox.pack(padx=10, pady=10)
 4
 5# 插入初始數(shù)據(jù)
 6for item in ["Apple", "Banana", "Cherry", "Date"]:
 7    listbox.insert(tk.END, item)
 8
 9
10# 添加按鈕:選中操作
11def show_selected():
12    selected_indices = listbox.curselection()  # 獲取選中的索引
13    if selected_indices:
14        selected_items = [listbox.get(i) for i in selected_indices]
15        print(f"Selected items: {selected_items}")
16    else:
17        print("No item selected.")
18
19
20select_button = tk.Button(window, text="Show Selected", command=show_selected)
21select_button.pack(side=tk.LEFT, padx=5)
22
23
24# 添加按鈕:插入操作
25def insert_item():
26    new_item = entry.get()  # 獲取輸入框內(nèi)容
27    if new_item:
28        listbox.insert(tk.END, new_item)
29        entry.delete(0, tk.END)  # 清空輸入框
30
31
32entry = tk.Entry(window)
33entry.pack(side=tk.LEFT, padx=5)
34
35insert_button = tk.Button(window, text="Insert", command=insert_item)
36insert_button.pack(side=tk.LEFT, padx=5)
37
38
39# 添加按鈕:刪除操作
40def delete_item():
41    selected_indices = listbox.curselection()
42    if selected_indices:
43        for index in reversed(selected_indices):  # 從后往前刪除,避免索引錯(cuò)位
44            listbox.delete(index)
45    else:
46        print("No item selected to delete.")
47
48
49delete_button = tk.Button(window, text="Delete", command=delete_item)
50delete_button.pack(side=tk.LEFT, padx=5)

事件:

  • ListboxSelect: 選中項(xiàng)改變

(9) Scrollbar(滾動(dòng)條)

用途: 為其他組件添加滾動(dòng)功能  示例: 為T(mén)ext多行文本添加垂直和水平滾動(dòng)條

1# 設(shè)置 wrap=tk.NONE 以允許水平滾動(dòng)
 2text = tk.Text(window,wrap=tk.NONE)  
 3text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
 4
 5# 創(chuàng)建垂直滾動(dòng)條
 6vertical_scrollbar = tk.Scrollbar(window, orient=tk.VERTICAL, command=text.yview)
 7vertical_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
 8
 9# 創(chuàng)建水平滾動(dòng)條
10horizontal_scrollbar = tk.Scrollbar(window, orient=tk.HORIZONTAL, command=text.xview)
11horizontal_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
12
13# 配置 Text 小部件以使用滾動(dòng)條
14text.config(yscrollcommand=vertical_scrollbar.set, xscrollcommand=horizontal_scrollbar.set)
15
16# 添加一些示例文本
17for i in range(50):
18    text.insert(tk.END, f"Line {i + 1}: This is some example text.\n")

(10) Canvas(畫(huà)布)

用途: 繪制圖形或自定義界面  示例: 繪制圖形、加載圖片、鼠標(biāo)點(diǎn)擊生成小黑點(diǎn)

1# 創(chuàng)建 Canvas 小部件
 2canvas = tk.Canvas(window, width=400, height=300, bg="white")
 3canvas.pack(padx=10, pady=10)
 4
 5# 繪制一條線
 6canvas.create_line(50, 50, 200, 50, fill="blue", width=3)
 7
 8# 繪制一個(gè)矩形
 9canvas.create_rectangle(50, 100, 150, 150, outline="green", fill="yellow")
10
11# 繪制一個(gè)橢圓
12canvas.create_oval(200, 100, 300, 150, outline="red", fill="pink")
13
14# 繪制一個(gè)多邊形
15canvas.create_polygon(350, 100, 375, 150, 325, 150, fill="orange")
16
17# 添加文本
18canvas.create_text(200, 200, text="Hello, Canvas!", fnotallow=("Arial", 16), fill="purple")
19
20# 插入圖像(需要 PIL 庫(kù)支持)
21try:
22    from PIL import Image, ImageTk
23
24    # 加載圖像
25    image = Image.open("meinv.jpg")  # 替換為你的圖片路徑
26    photo = ImageTk.PhotoImage(image)
27
28    # 在 Canvas 上顯示圖像
29    canvas.create_image(200, 250, image=photo)
30    # 需要保持對(duì)圖像的引用,否則會(huì)被垃圾回收
31    canvas.image = photo
32except ImportError:
33    print("Pillow library is not installed. Cannot display images.")
34
35
36# 處理鼠標(biāo)點(diǎn)擊事件
37def on_canvas_click(event):
38    x, y = event.x, event.y
39    print(f"Mouse clicked at: ({x}, {y})")
40    # 在點(diǎn)擊位置繪制一個(gè)小圓圈
41    canvas.create_oval(x - 5, y - 5, x + 5, y + 5, fill="black")
42
43
44canvas.bind("<Button-1>", on_canvas_click)

(11) Menu(菜單)

用途: 創(chuàng)建主菜單欄  示例: 創(chuàng)建主菜單,文件、編輯、幫助及各子菜單和彈出消息

1def new_file():
 2    messagebox.showinfo("New File", "Create a new file.")
 3
 4def open_file():
 5    messagebox.showinfo("Open File", "Open an existing file.")
 6
 7def exit_app():
 8    if messagebox.askokcancel("Quit", "Do you want to quit?"):
 9        window.destroy()
10
11def about():
12    messagebox.showinfo("About", "This is a demonstration of Tkinter Menu widget.")
13
14
15# 創(chuàng)建菜單欄
16menu_bar = tk.Menu(window)
17
18# 添加“文件”菜單
19file_menu = tk.Menu(menu_bar, tearoff=0)
20file_menu.add_command(label="New", command=new_file)
21file_menu.add_command(label="Open", command=open_file)
22file_menu.add_separator()
23file_menu.add_command(label="Exit", command=exit_app)
24menu_bar.add_cascade(label="File", menu=file_menu)
25
26# 添加“編輯”菜單(此處僅作展示,未添加實(shí)際功能)
27edit_menu = tk.Menu(menu_bar, tearoff=0)
28edit_menu.add_command(label="Cut")
29edit_menu.add_command(label="Copy")
30edit_menu.add_command(label="Paste")
31menu_bar.add_cascade(label="Edit", menu=edit_menu)
32
33# 添加“幫助”菜單
34help_menu = tk.Menu(menu_bar, tearoff=0)
35help_menu.add_command(label="About", command=about)
36menu_bar.add_cascade(label="Help", menu=help_menu)
37
38# 將菜單欄設(shè)置到主窗口
39window.config(menu=menu_bar)

用途: 創(chuàng)建彈出菜單欄  示例: 窗口綁定右鍵 1左鍵 2、滑輪 3、右鍵

1def show_popup(event):
 2    # 顯示彈出菜單,指定位置為鼠標(biāo)點(diǎn)擊的位置
 3    popup_menu.post(event.x, event.y)
 4
 5
 6def option1_action():
 7    print("Option 1 selected")
 8
 9
10def option2_action():
11    print("Option 2 selected")
12
13
14def exit_app():
15    if messagebox.askokcancel("Quit", "Do you want to quit?"):
16        window.destroy()
17
18
19# 創(chuàng)建彈出菜單 tearoff=0 禁用菜單分離功能
20popup_menu = tk.Menu(window, tearoff=0)  
21popup_menu.add_command(label="Option 1", command=option1_action)
22popup_menu.add_command(label="Option 2", command=option2_action)
23# 添加分隔線
24popup_menu.add_separator()  
25popup_menu.add_command(label="Exit", command=exit_app)
26
27# 綁定右鍵點(diǎn)擊事件到主窗口 Button-3 表示鼠標(biāo)右鍵
28window.bind("<Button-3>", show_popup)

(12) Scale(滑塊)

用途: 通過(guò)滑塊選擇數(shù)值范圍  示例: RGB顏色取值及16進(jìn)制顏色碼

1def update_color(*args):
 2    """根據(jù) Scale 的值更新背景顏色并輸出十六進(jìn)制顏色碼"""
 3    # 獲取當(dāng)前 RGB 值
 4    red = red_var.get()
 5    green = green_var.get()
 6    blue = blue_var.get()
 7
 8    # 生成十六進(jìn)制顏色碼
 9    hex_color = f'#{red:02x}{green:02x}{blue:02x}'
10
11    # 更新 Canvas 背景顏色
12    canvas.config(bg=hex_color)
13
14    # 顯示十六進(jìn)制顏色碼
15    color_code_label.config(text=f"Hex Color: {hex_color}")
16
17
18# 創(chuàng)建一個(gè) Canvas 用于顯示背景顏色變化
19canvas = tk.Canvas(window, width=300, height=200, bg='#000000')
20canvas.pack(pady=10)
21
22# 創(chuàng)建三個(gè) Scale 小部件分別控制 RGB 顏色通道
23red_var = tk.IntVar()
24red_scale = tk.Scale(window, from_=0, to=255, orient=tk.HORIZONTAL, length=300,
25                     variable=red_var, label="Red", command=update_color)
26red_scale.pack(pady=5)
27
28green_var = tk.IntVar()
29green_scale = tk.Scale(window, from_=0, to=255, orient=tk.HORIZONTAL, length=300,
30                       variable=green_var, label="Green", command=update_color)
31green_scale.pack(pady=5)
32
33blue_var = tk.IntVar()
34blue_scale = tk.Scale(window, from_=0, to=255, orient=tk.HORIZONTAL, length=300,
35                      variable=blue_var, label="Blue", command=update_color)
36blue_scale.pack(pady=5)
37
38# 創(chuàng)建一個(gè)標(biāo)簽用于顯示當(dāng)前十六進(jìn)制顏色碼
39color_code_label = tk.Label(window, text="Hex Color: #000000", fnotallow=("Arial", 14))
40color_code_label.pack(pady=10)
41
42# 設(shè)置初始值
43red_var.set(0)
44green_var.set(0)
45blue_var.set(0)

(13) Spinbox(數(shù)字輸入框)

用途: 數(shù)字選擇輸入  示例: 通過(guò)數(shù)值輸入框進(jìn)行RGB顏色、輸出十六進(jìn)制顏色碼

1def update_color():
 2    """根據(jù) Spinbox 的值更新背景顏色并輸出十六進(jìn)制顏色碼"""
 3    # 獲取當(dāng)前 RGB 值
 4    red = int(red_spinbox.get())
 5    green = int(green_spinbox.get())
 6    blue = int(blue_spinbox.get())
 7
 8    # 生成十六進(jìn)制顏色碼
 9    hex_color = f'#{red:02x}{green:02x}{blue:02x}'
10
11    # 更新 Canvas 背景顏色
12    canvas.config(bg=hex_color)
13
14    # 顯示十六進(jìn)制顏色碼
15    color_code_label.config(text=f"Hex Color: {hex_color}")
16
17
18# 創(chuàng)建一個(gè) Canvas 用于顯示背景顏色變化
19canvas = tk.Canvas(window, width=300, height=200, bg='#000000')
20canvas.pack(pady=10)
21
22# 創(chuàng)建三個(gè) Spinbox 控制 RGB 顏色通道
23red_label = tk.Label(window, text="Red")
24red_label.pack()
25red_spinbox = tk.Spinbox(window, from_=0, to=255, command=update_color)
26red_spinbox.pack()
27
28green_label = tk.Label(window, text="Green")
29green_label.pack()
30green_spinbox = tk.Spinbox(window, from_=0, to=255, command=update_color)
31green_spinbox.pack()
32
33blue_label = tk.Label(window, text="Blue")
34blue_label.pack()
35blue_spinbox = tk.Spinbox(window, from_=0, to=255, command=update_color)
36blue_spinbox.pack()
37
38# 創(chuàng)建一個(gè)標(biāo)簽用于顯示當(dāng)前十六進(jìn)制顏色碼
39color_code_label = tk.Label(window, text="Hex Color: #000000", fnotallow=("Arial", 14))
40color_code_label.pack(pady=10)
41
42# 設(shè)置初始值
43red_spinbox.delete(0, tk.END)
44red_spinbox.insert(0, "0")
45green_spinbox.delete(0, tk.END)
46green_spinbox.insert(0, "0")
47blue_spinbox.delete(0, tk.END)
48blue_spinbox.insert(0, "0")

(14) Message(消息框)

用途: 顯示多行文本(自動(dòng)換行)  示例: 各種消息提示框

1def show_info():
 2    messagebox.showinfo(title="信息", message="這是一個(gè)信息框")
 3
 4def show_warning():
 5    messagebox.showwarning(title="警告", message="這是一個(gè)警告框")
 6
 7def show_error():
 8    messagebox.showerror(title="錯(cuò)誤", message="這是一個(gè)錯(cuò)誤框")
 9
10def ask_question():
11    response = messagebox.askquestion(title="確認(rèn)", message="你確定要執(zhí)行此操作嗎?")
12    print(f"用戶選擇了: {response}")
13
14def ask_yes_no():
15    response = messagebox.askyesno(title="是/否", message="請(qǐng)選擇是或否?")
16    print(f"用戶選擇了: {'是' if response else '否'}")
17
18def ask_retry_cancel():
19    response = messagebox.askretrycancel(title="重試/取消", message="操作失敗,是否重試?")
20    print(f"用戶選擇了: {'重試' if response else '取消'}")
21
22def ask_yes_no_cancel():
23    response = messagebox.askyesnocancel(title="是/否/取消", message="請(qǐng)選擇是、否或取消?")
24    if response isTrue:
25        print("用戶選擇了 是")
26    elif response isFalse:
27        print("用戶選擇了 否")
28    else:
29        print("用戶選擇了 取消")
30
31
32# 添加按鈕并綁定函數(shù)
33tk.Button(window, text="顯示信息", command=show_info).pack()
34tk.Button(window, text="顯示警告", command=show_warning).pack()
35tk.Button(window, text="顯示錯(cuò)誤", command=show_error).pack()
36tk.Button(window, text="詢問(wèn)問(wèn)題", command=ask_question).pack()
37tk.Button(window, text="是/否", command=ask_yes_no).pack()
38Button(window, text="重試/取消", command=ask_retry_cancel).pack()
39Button(window, text="是/否/取消",command=ask_yes_no_cancel).pack()

(15) Dialog(對(duì)話彈窗)

用途: 各種對(duì)話框和用戶交互,打開(kāi)、保存文件、顏色選擇、輸入框示例:

1def open_file_dialog():
 2    """打開(kāi)文件對(duì)話框"""
 3    filepath = filedialog.askopenfilename(
 4        title="選擇一個(gè)文件",
 5        filetypes=(("文本文件", "*.txt"), ("所有文件", "*.*"))
 6    )
 7    if filepath:
 8        messagebox.showinfo("已選文件", f"你選擇了: {filepath}")
 9
10def save_file_dialog():
11    """保存文件對(duì)話框"""
12    filepath = filedialog.asksaveasfilename(
13        title="保存文件",
14        defaultextensinotallow=".txt",
15        filetypes=(("文本文件", "*.txt"), ("所有文件", "*.*"))
16    )
17    if filepath:
18        messagebox.showinfo("保存文件", f"文件將被保存為: {filepath}")
19
20def choose_color():
21    """顏色選擇對(duì)話框"""
22    color_code = colorchooser.askcolor(title="選擇顏色")
23    if color_code[0] isnotNone:
24        # color_code 返回一個(gè)元組 (RGB, HEX)
25        messagebox.showinfo("選擇的顏色", f"你選擇的顏色是: {color_code[1]}")
26
27def prompt_string():
28    """簡(jiǎn)單輸入對(duì)話框"""
29    user_input = simpledialog.askstring("輸入字符串", "請(qǐng)輸入你的名字:")
30    if user_input:
31        messagebox.showinfo("結(jié)果", f"你輸入的名字是: {user_input}")
32    else:
33        messagebox.showwarning("警告", "你沒(méi)有輸入任何內(nèi)容!")
34
35
36
37# 添加按鈕并綁定函數(shù)
38tk.Button(window, text="打開(kāi)文件", command=open_file_dialog).pack(pady=5)
39tk.Button(window, text="保存文件", command=save_file_dialog).pack(pady=5)
40tk.Button(window, text="選擇顏色", command=choose_color).pack(pady=5)
41tk.Button(window, text="輸入字符串", command=prompt_string).pack(pady=5)

四、ttk 擴(kuò)展組件及其它

除了基礎(chǔ)組件外,Tkinter的 ttk 模塊提供更現(xiàn)代樣式的組件:

  • ttk.Combobox: 下拉選擇框
  • ttk.Treeview: 樹(shù)形列表
  • ttk.Progressbar: 進(jìn)度條
1from tkinter import ttk
2combo = ttk.Combobox(root, values=["A", "B", "C"])
3combo.pack()

五、`Tkinter`不足

  • 它的界面設(shè)計(jì)相對(duì)簡(jiǎn)陋,不如其他GUI庫(kù)(如Qt和wxPython)美觀。
  • 它的文檔不夠完善,有時(shí)需要查閱第三方資料才能解決問(wèn)題。
  • 它的社區(qū)不夠活躍,難以獲得及時(shí)的技術(shù)支持。

示例:比如Tkinter不支持系統(tǒng)托盤(pán)。

1pip install pystray

創(chuàng)建一個(gè)Form,當(dāng)窗口隱藏時(shí),進(jìn)入系統(tǒng)托盤(pán)。點(diǎn)擊托盤(pán)彈出菜單:

1def create_tray_icon():
 2    """創(chuàng)建系統(tǒng)托盤(pán)圖標(biāo)"""
 3    # 創(chuàng)建一個(gè)簡(jiǎn)單的圖像作為托盤(pán)圖標(biāo)
 4    image = Image.open("icon.png")  # 替換為你的圖標(biāo)文件路徑
 5    menu = (
 6        pystray.MenuItem("顯示窗口", show_window),
 7        pystray.MenuItem("退出", quit_app)
 8    )
 9
10    # 創(chuàng)建托盤(pán)圖標(biāo)
11    icon = pystray.Icon("name", image, "My System Tray App", menu)
12    icon.run()
13
14def show_window():
15    """顯示主窗口"""
16    window.deiconify()  # 恢復(fù)隱藏的窗口
17
18def hide_window():
19    """隱藏主窗口到系統(tǒng)托盤(pán)"""
20    window.withdraw()  # 隱藏窗口
21
22def quit_app(icnotallow=None):
23    """退出應(yīng)用程序"""
24    if icon:
25        icon.stop()  # 停止托盤(pán)圖標(biāo)線程
26    window.quit()  # 退出 Tkinter 主循環(huán)
27
28
29
30# 添加按鈕用于隱藏窗口到托盤(pán)
31hide_button = tk.Button(window, text="隱藏到托盤(pán)", command=hide_window)
32hide_button.pack(pady=20)
33
34# 啟動(dòng)系統(tǒng)托盤(pán)線程
35tray_thread = Thread(target=create_tray_icon, daemnotallow=True)
36tray_thread.start()

以上就是本文關(guān)于Python Tkinter庫(kù)入門(mén)指南的全部?jī)?nèi)容。希望本文能夠幫助您快速掌握Tkinter庫(kù)的基礎(chǔ)知識(shí),并能夠運(yùn)用所學(xué)知識(shí)來(lái)創(chuàng)建自己的圖形用戶界面應(yīng)用程序。

責(zé)任編輯:趙寧寧 來(lái)源: 程序員老朱
相關(guān)推薦

2022-07-15 16:31:49

Postman測(cè)試

2021-10-18 11:58:56

負(fù)載均衡虛擬機(jī)

2022-09-06 08:02:40

死鎖順序鎖輪詢鎖

2024-03-07 18:11:39

Golang采集鏈接

2021-01-19 05:49:44

DNS協(xié)議

2022-09-14 09:01:55

shell可視化

2024-07-15 07:55:00

2020-07-15 08:57:40

HTTPSTCP協(xié)議

2020-11-16 10:47:14

FreeRTOS應(yīng)用嵌入式

2020-07-09 07:54:35

ThreadPoolE線程池

2022-10-10 08:35:17

kafka工作機(jī)制消息發(fā)送

2022-07-19 16:03:14

KubernetesLinux

2024-05-10 12:59:58

PyTorch人工智能

2023-06-12 08:49:12

RocketMQ消費(fèi)邏輯

2021-08-26 05:02:50

分布式設(shè)計(jì)

2024-01-11 09:53:31

面試C++

2022-09-08 10:14:29

人臉識(shí)別算法

2024-01-05 08:30:26

自動(dòng)駕駛算法

2022-02-15 18:45:35

Linux進(jìn)程調(diào)度器

2021-06-04 07:27:24

sourcemap前端技術(shù)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)