Home > OS >  How to make a "while True" loop work in a tkinter-based game?
How to make a "while True" loop work in a tkinter-based game?

Time:04-28

I want to make a simple clicker game and one of my upgrades needs to be constantly running in background. I tried while True: loop but it just doesn't work and python crushes. What's wrong?

from time import sleep
import tkinter as tk


window=tk.Tk()
window.columnconfigure([0,4], minsize=60,)

def click():
    points["text"]=1 int(points["text"])

def up3():
    if int(points["text"])>=int(cost3["text"]):
        lvl3["text"]=int(lvl3["text"]) 1
        points["text"]=int(points["text"])-int(cost3["text"])
        cost3["text"]=int(int(cost3["text"])*2)
        while True:
            points["text"]=int(points["text"]) 100*int(lvl3["text"])
            sleep(1)

# points and click button
points=tk.Label(text="10000000")
points.grid(row=0,column=0,columnspan=5,sticky="WE")
tk.Button(text="click!",command=click).grid(row=1,column=0,columnspan=5,sticky="WE")

# upgrade 3
tk.Button(text="passive points",command=up3).grid(row=5,sticky="WE",column=0)
tk.Label(text=" 100/s").grid(row=5,column=1)
cost3=tk.Label(text="10000")
cost3.grid(row=5,column=3)
lvl3=tk.Label(text="1")
lvl3.grid(row=5,column=4)

window.mainloop()

CodePudding user response:

Here's how to use the universal widget method after() to effectively perform a while True: infinite loop that won't interfere with the execution of the rest of your tkinter app.

I've added a function called updater() which performs the actions you want and then reschedules another call to itself after a 1000 milliseconds (i.e. 1 second) delay.

This is what some of the answers to the linked question in @Random Davis's comment suggest doing, as do I.

import tkinter as tk


window=tk.Tk()
window.columnconfigure([0,4], minsize=60,)

def click():
    points["text"] = int(points["text"])   1

def up3():
    if int(points["text"]) >= int(cost3["text"]):
        lvl3["text"] = int(lvl3["text"])   1
        points["text"] = int(points["text"]) - int(cost3["text"])
        cost3["text"] = int(int(cost3["text"]) * 2)
        updater()  # Start update loop.

def updater():
    points["text"] = int(points["text"])   100*int(lvl3["text"])
    window.after(1000, updater)  # Call again in 1 sec.

# points and click button
points = tk.Label(text="10000000")
points.grid(row=0, column=0, columnspan=5, sticky="WE")
tk.Button(text="click!",command=click).grid(row=1, column=0, columnspan=5, sticky="WE")

# upgrade 3
tk.Button(text="passive points", command=up3).grid(row=5, sticky="WE", column=0)
tk.Label(text=" 100/s").grid(row=5, column=1)
cost3 = tk.Label(text="10000")
cost3.grid(row=5, column=3)
lvl3 = tk.Label(text="1")
lvl3.grid(row=5, column=4)

window.mainloop()

CodePudding user response:

Use the threading module So the While True loop runs in an another thread https://docs.python.org/3/library/threading.html

  • Related