How to make Python tkinter function non-stop

Asked 2 years ago, Updated 2 years ago, 65 views

I'm trying to make it snow on canvas, but if I draw a dot on canvas according to the def function, the dot falls like snow, but if I draw a different dot, the original snow stops and the new dot goes down... Is there a way to lower the original point and lower the new point? I think I need to separate the def function, so I would appreciate it if you could give me some advice.

python tkinter

2022-09-22 17:54

1 Answers

This is an example of thread utilization.

But if you test it, it's not going to be as good as you want.

There is a GIL problem, as is logic.

Even if you create threads, only one Python object can be accessed at the same time. In other words, even if there are four cores, only one is used, and Python threads are not executed in a parallel manner except for io tasks.

import tkinter
from random import randint
import threading

window = tkinter.Tk()

img = tkinter.PhotoImage (file="image file")
canvas = tkinter.Canvas(window, width=img.width(), height=img.height())
canvas.create_image(0, 0, anchor="nw", image=img)
canvas.pack()

steps = int((img.height() + 30) / 30)

def drawLine(event):
    def _process():
        x, y = event.x, event.y
        r = randint(2, 4)
        S = canvas.create_oval(x-y, y-r, x+r, y+r, fill="white", outline="white")
        canvas.itemconfig(S)
        for_in range (steps): # Remove infinite iterations   
            canvas.move(S, 0, 30)
            canvas.after(100)
            canvas.update()
    th = threading.Thread(target=_process)
    th.start()

canvas.bind("<ButtonRelease-1>", drawLine)

window.mainloop()


2022-09-22 17:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.