Tkinter刷新画布

2024-10-02 00:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想在光标后面创建一条线。我不想有前几帧的痕迹

root = Tk()
canvas = Canvas(root, width=720, height=720)

def mouseGetPos():
    global root
    relX = root.winfo_pointerx() - root.winfo_rootx()
    relY = root.winfo_pointery() - root.winfo_rooty()
    return [relX, relY]

while True:
    canvas.pack()
    canvas.create_line(0,0, mouseGetPos()[0],mouseGetPos()[1])
    time.sleep(1/100)
    root.update()

如何更新/刷新画布?我用这个做游戏


Tags: defrootwidthglobaltkcanvasheight痕迹
3条回答

编写tkinter程序的正确方法是使用mainloop,而不是创建自己的游戏循环。这样,您就不必强制进行任何更新,屏幕将在事件之间自动更新

然后可以绑定一个函数,以便在鼠标移动时调用。每次tkinter检测到事件时,都会调用您的函数

下面是一个工作示例:

import tkinter as tk

def drawLine(event):
    item_id = canvas.find_withtag("the_line")
    if item_id:
        canvas.coords("the_line", 0, 0, event.x, event.y)
    else:
        canvas.create_line(0, 0, event.x, event.y, tags=("the_line",))

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack(fill="both", expand=True)
canvas.bind("<Motion>", drawLine)

root.mainloop()

这对我很有用:

while True:
    canvas.pack()
    canvas.create_line(0,0, mouseGetPos()[0],mouseGetPos()[1],tags='line')
    time.sleep(1/100),
    root.update()
    canvas.delete('line')

制作一个标记-“行”,然后删除该行,以便获得所需的结果

我认为这是使用事件的最简单解决方案。这是基于@BryanOakley的答案

import tkinter as tk

def draw_line(event:tk.Event) -> None:
    # Configure the lines' coordinates:
    canvas.coords("the_line", 0, 0, event.x, event.y)
    # event.x and event.y are the mouse's poition
        

root = tk.Tk()
canvas = tk.Canvas(root, highlightthickness=0)
canvas.pack(fill="both", expand=True)

# Create a line that's going to be invisible.
canvas.create_line(-10, -10, -10, -10, tags=("the_line", ))

# Each time the mouse moves over the canvas call `draw_line`
canvas.bind("<Motion>", draw_line)

root.mainloop()

相关问题 更多 >

    热门问题