Featured image of post Python Basic 19 Tkinter 基本UI界面创建

Python Basic 19 Tkinter 基本UI界面创建

本篇文章主要 Python 用 Tkinter 创建基本UI界面

Tkinter 是 Python 自带的 GUI 工具包,让我们可以轻松创建图形用户界面。下面我将详细介绍如何使用 Tkinter 创建基本界面!( •̀ ω •́ )✧

最简单的窗口 🏗️

1
2
3
4
5
6
7
8
9
import tkinter as tk

# 创建一个主窗口
root = tk.Tk()
root.title("我的第一个Tkinter窗口")  # 设置标题
root.geometry("400x300")  # 设置窗口大小

# 进入主事件循环
root.mainloop()

运行效果:会弹出一个 400x300 大小的空窗口!٩(◕‿◕。)۶

添加控件 🎛️

添加标签 (Label)

1
2
label = tk.Label(root, text="你好,Tkinter!", font=("Arial", 20), fg="blue")
label.pack()  # 将标签放入窗口

添加按钮 (Button)

1
2
3
4
5
def button_click():
    label.config(text="按钮被点击啦!(ノ≧∀≦)ノ")

button = tk.Button(root, text="点我", command=button_click, bg="yellow")
button.pack(pady=10)  # pady添加垂直间距

添加输入框 (Entry)

1
2
3
4
5
6
7
8
9
entry = tk.Entry(root, width=30)
entry.pack(pady=10)

def show_text():
    user_input = entry.get()
    label.config(text=f"你输入了: {user_input}")

show_button = tk.Button(root, text="显示输入", command=show_text)
show_button.pack()

布局管理 📐

Tkinter 有三种布局方式:

pack() 布局

1
2
# 上面例子中已经使用了pack()
label.pack(side="top", padx=10, pady=5)  # 可以指定位置和边距

grid() 布局

1
2
3
4
5
6
# 更精确的网格布局
name_label = tk.Label(root, text="姓名:")
name_label.grid(row=0, column=0, sticky="e")  # sticky对齐方式

name_entry = tk.Entry(root)
name_entry.grid(row=0, column=1, padx=5, pady=5)

place() 布局

1
2
3
# 绝对定位(像素)
custom_button = tk.Button(root, text="绝对定位", bg="#ffcc00")
custom_button.place(x=200, y=150, width=100, height=50)

常见控件大集合 🧩

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 复选框
check_var = tk.IntVar()
check = tk.Checkbutton(root, text="同意条款", variable=check_var)
check.pack()

# 单选按钮
radio_var = tk.StringVar()
radio1 = tk.Radiobutton(root, text="选项1", variable=radio_var, value="1")
radio2 = tk.Radiobutton(root, text="选项2", variable=radio_var, value="2")
radio1.pack()
radio2.pack()

# 列表框
listbox = tk.Listbox(root)
for item in ["Python", "Java", "C++", "JavaScript"]:
    listbox.insert(tk.END, item)
listbox.pack()

# 滚动条
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

菜单栏 🍔

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
menubar = tk.Menu(root)

# 文件菜单
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="新建")
filemenu.add_command(label="打开")
filemenu.add_separator()
filemenu.add_command(label="退出", command=root.quit)
menubar.add_cascade(label="文件", menu=filemenu)

# 编辑菜单
editmenu = tk.Menu(menubar, tearoff=0)
editmenu.add_command(label="撤销")
editmenu.add_command(label="重做")
menubar.add_cascade(label="编辑", menu=editmenu)

root.config(menu=menubar)

消息框 📨

1
2
3
4
5
6
7
from tkinter import messagebox

def show_info():
    messagebox.showinfo("提示", "这是一个信息提示框!(●'◡'●)")

info_button = tk.Button(root, text="显示信息", command=show_info)
info_button.pack()

Tkinter 还有很多强大的功能等你探索!(๑•̀ㅂ•́)و✧ 建议动手试试这些代码,然后逐步添加自己的功能哦~

Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计