源码案例来自洪锦魁先生所著《Python GUI设计 tkinter菜鸟编程》一书。本手册中相当一部分代码将来自本书。

  1. import tkinter as tk
  2. print(tk.TkVersion)

最简单的窗体

  1. import tkinter as tk
  2. root = tk.Tk()
  3. root.mainloop()

另一种写法

  1. from tkinter import *
  2. root = Tk()
  3. root.mainloop()

但是,好像一般不推荐 import *这种写法。

  1. root = tk.Tk()
  2. root.geometry("300x400+200+200")
  3. root.minsize(100,100)
  4. root.maxsize(500,500)
  5. root.config(bg="yellow")
  6. root.mainloop()

固定宽高

  1. import tkinter as tk
  2. root = tk.Tk()
  3. root.geometry("300x400+200+200")
  4. root.minsize(100,100)
  5. root.maxsize(500,500)
  6. root.config(bg="yellow")
  7. root.resizable(0,0)
  8. root.mainloop()

自定义窗口图标

  1. import tkinter as tk
  2. root = tk.Tk()
  3. root.geometry("300x400+200+200")
  4. root.minsize(100,100)
  5. root.maxsize(500,500)
  6. root.config(bg="yellow")
  7. root.resizable(0,0)
  8. root.iconbitmap("w6.ico")
  9. root.mainloop()

利用格式化字符串参数化设置窗口尺寸

书上所写的代码,实际运行出错,查找资料,发现一种叫做f-string的格式化字符串表述形式,试验后,正确运行。

  1. import tkinter as tk
  2. root = tk.Tk()
  3. w = 600
  4. h = 200
  5. x = 700
  6. y = 200
  7. root.geometry(f"{w}x{h}+{x}+{y}")
  8. root.mainloop()
  1. screenWidth = root.winfo_screenwidth()
  2. screenHeight = root.winfo_screenheight()
  3. w = 600
  4. h = 200
  5. x = (screenWidth - w)/2
  6. y = (screenHeight - h)/2
  7. root.geometry(f"{w}x{h}+{x}+{y}")
  8. root.mainloop()

会报错,因为出现了小数点,加上int之后就可以正常运行了。
image.png

label

  1. lab1 = tk.Label(
  2. root,
  3. text="1123",
  4. bg="yellow",
  5. width=10,
  6. height=3,
  7. anchor="nw"
  8. ).pack()

文字换行

  1. lab1 = tk.Label(
  2. root,
  3. text="11231212121212",
  4. bg="yellow",
  5. width=10, #单位:字符宽
  6. height=3, #单位:字符高
  7. anchor="nw",
  8. wraplength = 40 #单位:像素
  9. ).pack()
  1. lab1 = tk.Label(
  2. root,
  3. text="11231212121212",
  4. bg="yellow",
  5. width=10, #单位:字符宽
  6. height=3, #单位:字符高
  7. anchor="nw",
  8. wraplength = 40, #单位:像素
  9. justify = "right"
  10. ).pack()