我正在研究 TSP 問題并從檔案中讀取一些點(必須使用我給出的點)并希望將這些點繪制到 GUI 上。但問題是這些點都只有 2 位數字,當我使用 tkinter.Canvas() 繪制它們時,它們看起來都很臟而且很小,幾乎就像它們相互重疊一樣。
像這樣:

我遇到了問題,但只是想使用這個 GUI 來顯示它正在作業,而不是將它全部輸出到控制臺,但不能導致它在繪制線條時看起來更糟。那么有什么方法可以放大畫布或修改點以某種方式使它們看起來更好。我真的可以做任何事情還是我只是把它全部扔到控制臺?
uj5u.com熱心網友回復:
給定節點值在任何坐標系中以 (0, 0) 為中心,您需要操縱給定的坐標以符合您的螢屏和畫布正確渲染繪圖所需的內容
您可以通過標量因子重新縮放您的點,然后將原點平移到螢屏的中心(或任何位置),以便更輕松地將它們可視化:
也許是這樣的:

import tkinter as tk
WIDTH = 600
HEIGHT = 400
given_nodes = ((-1, -1), (-1, 1), (1, 1), (1, -1), (0, -1.5))
scale = 100
scaled_nodes = [(x * scale, y * scale) for x, y in given_nodes]
translated_to_center_nodes = [(x WIDTH/2, y HEIGHT/2) for x, y in scaled_nodes]
app = tk.Tk()
canvas = tk.Canvas(app, width=WIDTH, height=HEIGHT, bg='cyan')
canvas.pack()
# Draw connecting lines
line_nodes = translated_to_center_nodes [translated_to_center_nodes[0]]
for idx, node in enumerate(line_nodes[:-1]):
x0, y0 = node
x1, y1 = line_nodes[idx 1]
canvas.create_line(x0, y0, x1, y1, fill='black')
# draw nodes
for node in translated_to_center_nodes:
x, y = node
dx, dy = 2, 2
canvas.create_oval(x-dx, y dy, x dx, y-dy, fill='white')
# draw origin & coordinate system at rescaled drawing scale
canvas.create_line(0, 0, 0 scale, 0, width=9, fill='blue', arrow=tk.LAST)
canvas.create_line(0, 0, 0, scale, width=9, fill='blue', arrow=tk.LAST)
canvas.create_text(40, 40, text='SCALED\nCANVAS\nORIGIN')
# draw moved origin & coordinate system at rescaled drawing scale
canvas.create_line(0, HEIGHT/2, WIDTH, HEIGHT/2, fill='black', dash=(1, 3))
canvas.create_line(WIDTH/2, HEIGHT/2, WIDTH/2 scale, HEIGHT/2, width=3, fill='black', arrow=tk.LAST)
canvas.create_line(WIDTH/2, 0, WIDTH/2, HEIGHT, fill='black', dash=(1, 3))
canvas.create_line(WIDTH/2, HEIGHT/2, WIDTH/2, HEIGHT/2 scale, width=3, fill='black', arrow=tk.LAST)
canvas.create_text(WIDTH/2, HEIGHT/2, text='MOVED\nORIGIN')
if __name__ == '__main__':
app.mainloop()
This is commonly done with matrix multiplication and homogeneous coordinates (look it up), but the machinery needed to demonstrate a simple example is a little too heavy. The process of using the coordinates of an object and drawing it at scale, at the proper place, maybe rotated of skewed is called instantiation (look it up too!)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/350119.html
