Skip to content

4 、绘图


一、主框架🧀

import tkinter as tk

# 创建主窗口
root = tk.Tk()
root.title("Tkinter Graphics Example")

# 创建画布
canvasWidth = 400
canvasHeight = 200
canvas = tk.Canvas(root, width=canvasWidth, height=canvasHeight, bg='white')
canvas.pack()

# 运行主事件循环
root.mainloop()

二、画图🧀

1、画线🧀

canvas.create_line(20, 53, app.width / 2, app.height / 2, fill='red')

2、画长方形🧀

  • 层级关系是后定义会覆盖在先定义的之上
canvas.create_rectangle(60, 53, app.width / 3 * 2, app.height / 2, fill='red')

3、其他基本操作🧀

1
2
3
4
5
canvas.create_oval(90, 50, 150, 150, fill='orange')
canvas.create_text(120, 100,
                   text='Hello World!',
                   fill='blue',
                   font=('Arial', 20))
  • 居中操作
1
2
3
4
5
6
7
8
# 居中
margin = 50
canvas.create_rectangle(margin, margin, canvasWidth - margin, canvasHeight - margin, fill='lightgreen')

# 居中的其他方式
(cx, cy) = (canvasWidth // 2, canvasHeight // 2)
(rectWidth, rectHeight) = (100, 60)
canvas.create_rectangle(cx - rectWidth / 2, cy - rectHeight / 2, cx + rectWidth / 2, cy + rectHeight / 2, fill='red')
  • 动态调整大小
1
2
3
textSize = canvasWidth // 5 # 一定调整为整数
canvas.create_text(canvasWidth / 2, canvasHeight / 2, text="Hello",
font=f'Arial {textSize} bold', fill='orange')
1
2
3
4
5
6
7
8
9
(cx, cy, radius) = (canvasWidth / 2, canvasHeight / 2, min(canvasWidth, canvasHeight) / 3)
canvas.create_oval(cx - radius, cy - radius, cx + radius, cy + radius, fill='lightyellow')
radius *= 0.85
for hour in range(12):
    hourAngle = math.pi / 2 - (2 * math.pi * hour / 12)
    hourX = cx + radius * math.cos(hourAngle)
    hourY = cy - radius * math.sin(hourAngle)
    label = str(hour if hour > 0 else 12)
    canvas.create_text(hourX, hourY, text=label)