常用组件
创建窗口
1 2 3 4 5 6 7 8 9
| import tkinter as tk import tkinter.ttk as ttk
root = tk.Tk() root.wm_title('窗口标题') root.geometry('1000x600') root.resizable(False, False)
root.mainloop()
|
Frame
块,可以理解为html的div
1 2 3 4
| frame = tk.Frame(root)
frame.pack()
|
按钮
1 2 3 4 5 6 7 8
| btn = ttk.Button(frame, text="按钮文案")
def action(): print("click")
btn[tk.COMMAND] = action
|
loading
上述的前提是action不阻塞,如果action阻塞,就会影响整个UI,此时建议使用多线程,并且配合loading
- 对
btn['text']和btn['state']也需要等到action完全结束才会显示出来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import threading
def slow_action_button(frame, action) -> tk.Entry: text = "提交" btn = ttk.Button(frame, text=text)
def slow_action(): try: action() finally: btn['state'] = tk.NORMAL btn['text'] = text
def wrapper(): btn['text'] = "提交中..." btn['state'] = tk.DISABLED threading.Thread(target=slow_action).start() btn[tk.COMMAND] = wrapper; return btn
|
文本输入
1 2 3 4 5 6 7 8
| text_input = tk.Text(root, height=15)
input_value = text_input.get()
text_input.delete(1.0, tk.END) text_input.insert(1.0, 'new value')
|
Label
1
| label = ttk.Label(root, text="需要帮助?请联系作者", foreground='gray')
|
布局
pack默认从上到下,居中排列
1 2 3
| 1.pack() 2.pack() 3.pack()
|
设置标题的icon和任务栏icon
使用png图片
1 2 3 4
| icon_base64 = "icon base64 data"
image = tk.PhotoImage(data=base64.b64decode(icon_base64)) root.iconphoto(True, image)
|
icon的base64使用以下方式获取
1 2 3 4 5 6
| from base64 import b64encode import sys
filename = sys.argv[1] with open(filename, "rb") as f: print(b64encode(f.read()).decode("ascii"))
|
高分辨率缩放
1 2 3 4 5
| import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1) ScaleFactor=ctypes.windll.shcore.GetScaleFactorForDevice(0) root.tk.call('tk', 'scaling', ScaleFactor/75)
|
打包成exe文件
1 2 3 4
| pip install pyinstaller
pyinstaller -w -F .\payafteruse-helper.py
|
-w: 窗口应用,不展示命令行-F: 单个可执行文件
参考