【问题标题】:Using tkinter how do you have a set of coordinates always updating?使用 tkinter 如何让一组坐标始终更新?
【发布时间】:2021-05-28 21:51:14
【问题描述】:

我想在屏幕上不断地绘制一组对象,其坐标由不断变化的数字列表确定。我正在使用 JSON 文件来读取坐标。 JSON 文件将如下所示:

{"coords_1": ["0", "0", "150", "120", "130", "180", "210", "160", "150", "30", "100", "20"],
"coords_2": ["450", "0", "250", "120", "240", "180", "210", "200", "150", "150", "100", "20"]}

我的 Python 代码现在看起来像这样

import json
from tkinter import *

def read(number):
    with open("coords.json", "r") as f:
        data = f.read()
    json_object = json.loads(data)
    s = "coords_"
    s += str(number)
    return json_object[s]


root = Tk()
root.geometry('500x500')

canvas = Canvas(root, height = 500, width = 500)

#ALWAYS UPDATE THIS
object_1 = canvas.create_polygon(read(1), outline="blue", fill="orange", width=2)
object_2 = canvas.create_polygon(read(2), outline="blue", fill="green", width=2)

canvas.place(x=0,y=0)
root.mainloop()

这很好用,但是,我希望能够更改 JSON 文件中的数据,从而更改对象的位置,但我无法做到。有谁知道这怎么可能?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    感谢tkinter root.mainloop with While True loop这个帖子,我解决了这个问题

    def repeat():
        object_1 = canvas.create_polygon(read(2), outline="blue", fill="orange", width=2)
        root.after(1000, repeat)
    
    root.after(1000, repeat)
    

    【讨论】:

    • 但是你每秒都在创建 new 多边形。
    • @acw1668 是的,没有写在代码中,但我也使用canvas.delete
    • 您不需要删除和重新创建,只需创建一次并更新坐标。
    猜你喜欢
    • 2020-03-06
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多