源码案例来自洪锦魁先生所著《Python GUI设计 tkinter菜鸟编程》一书。本手册中相当一部分代码将来自本书。
import tkinter as tk
print(tk.TkVersion)
最简单的窗体
import tkinter as tk
root = tk.Tk()
root.mainloop()
另一种写法
from tkinter import *
root = Tk()
root.mainloop()
但是,好像一般不推荐 import *这种写法。
root = tk.Tk()
root.geometry("300x400+200+200")
root.minsize(100,100)
root.maxsize(500,500)
root.config(bg="yellow")
root.mainloop()
固定宽高
import tkinter as tk
root = tk.Tk()
root.geometry("300x400+200+200")
root.minsize(100,100)
root.maxsize(500,500)
root.config(bg="yellow")
root.resizable(0,0)
root.mainloop()
自定义窗口图标
import tkinter as tk
root = tk.Tk()
root.geometry("300x400+200+200")
root.minsize(100,100)
root.maxsize(500,500)
root.config(bg="yellow")
root.resizable(0,0)
root.iconbitmap("w6.ico")
root.mainloop()
利用格式化字符串参数化设置窗口尺寸
书上所写的代码,实际运行出错,查找资料,发现一种叫做f-string的格式化字符串表述形式,试验后,正确运行。
import tkinter as tk
root = tk.Tk()
w = 600
h = 200
x = 700
y = 200
root.geometry(f"{w}x{h}+{x}+{y}")
root.mainloop()
screenWidth = root.winfo_screenwidth()
screenHeight = root.winfo_screenheight()
w = 600
h = 200
x = (screenWidth - w)/2
y = (screenHeight - h)/2
root.geometry(f"{w}x{h}+{x}+{y}")
root.mainloop()
会报错,因为出现了小数点,加上int之后就可以正常运行了。
label
lab1 = tk.Label(
root,
text="1123",
bg="yellow",
width=10,
height=3,
anchor="nw"
).pack()
文字换行
lab1 = tk.Label(
root,
text="11231212121212",
bg="yellow",
width=10, #单位:字符宽
height=3, #单位:字符高
anchor="nw",
wraplength = 40 #单位:像素
).pack()
lab1 = tk.Label(
root,
text="11231212121212",
bg="yellow",
width=10, #单位:字符宽
height=3, #单位:字符高
anchor="nw",
wraplength = 40, #单位:像素
justify = "right"
).pack()