试试这个:
import tkinter as tk
def resize_to_fill(canvas):
global bbox, xfactor, yfactor, factor, x, y # For debug only
# Get the [minx, miny, maxx, maxy] of all of the canvas items:
bbox = [float("inf"), float("inf"), float("-inf"), float("-inf")]
for id in canvas.find_all():
x1, y1, x2, y2 = canvas.bbox(id)
bbox[0] = min(bbox[0], x1)
bbox[1] = min(bbox[1], y1)
bbox[2] = max(bbox[2], x2)
bbox[3] = max(bbox[3], y2)
# This is needed to get the width and height of the canvas
canvas.update()
# Calculate the scale factors
xfactor = canvas.winfo_width() / (bbox[2]-bbox[0])
yfactor = canvas.winfo_height() / (bbox[3]-bbox[1])
canvas.moveto("all", 0, 0)
canvas.scale("all", 0, 0, xfactor, yfactor)
root = tk.Tk()
root.resizable(False, False)
canvas = tk.Canvas(root, bg="white", width=600, height=600,
highlightthickness=0)
canvas.pack()
# Change this to `False` if you want to test the second example
if True:
canvas.create_line(0, 0, 100, 0, fill="red")
canvas.create_line(100, 0, 100, 100, fill="blue")
canvas.create_line(100, 100, 0, 100, fill="black")
canvas.create_line(0, 100, 0, 0, fill="green")
else:
canvas.create_line(50, 50, 100, 50, fill="red")
canvas.create_line(100, 50, 100, 100, fill="blue")
canvas.create_line(100, 100, 50, 100, fill="black")
canvas.create_line(50, 100, 50, 50, fill="green")
button = tk.Button(root, text="Resize to fit canvas",
command=lambda: resize_to_fill(canvas))
button.pack(fill="x")
root.mainloop()
主要是数学,但基本上我所做的是:
- 获取所有对象的
min(x)、min(y)、max(x) 和max(y)
- 计算 x 和 y 因子
- 将所有对象移动到
(0, 0) 以使缩放更容易
- 通过
xfactor 和yfactor 从(0, 0) 缩放所有对象
注意事项:
- 它不保持纵横比。
- 有时它会在屏幕边缘之间留下空隙。我不知道为什么