Search code examples
pythontkintertkinter-button

Button causing Tkinter Window to Crash (Python)


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.


Solution

  • 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