1

I started learning python a few days ago and I have been messing around with Tkinter. I have been making a cookie-clicker type of game to practice what I learned. Everything worked except for a button that when clicked should start adding 1 point every 30 seconds.

I isolated the problem to this this:

from tkinter import *
import time

cookies_clicked = 0
cursors = 0

main_window = Tk()
main_window.title("Cookie Clicker")
main_window.geometry("900x500")


def click():
    global cookies_clicked
    global cursors
    cursors += 1
    while 0 == 0:
        print("test")# this is for me to check if the loop is working
        cookies_clicked += cursors
        time.sleep(30)


up_1 = Button(main_window, text="Upgrade 1", command=click)
up_1.place(x=410, y=100)

main_window.mainloop()

I know the loop is working when I click the button because "test" is printed every 30 seconds, but the Tkinter window stops responding completely.

Bluffyyy
  • 93
  • 5
  • 1
    That is the side effect of wresting control from `tkinter`. If you want a function to execute every 30 seconds you could consider using the `after()` method. – quamrana Aug 13 '22 at 15:58

1 Answers1

2

That is because you are waiting in the main thread so tkinter is also waits for 30 seconds so you can use Threadings

from threading import Thread
def click():
    global cookies_clicked
    global cursors
    cursors += 1
    while True:
        print("test")  # this is for me to check if the loop is working
        cookies_clicked += cursors
        time.sleep(30)


def _click():
    p = Thread(target=click)
    p.start()

up_1 = Button(main_window, text="Upgrade 1", command=_click)

Also instead of click you should use _click method

  • For something as simple as this, threading isn't necessary and adds a lot of complexity. While this will work, it's more complicated than it needs to be. – Bryan Oakley Aug 13 '22 at 16:28