2

I am making an incremental game (e.g. Cookie Clicker-style games) in Python, which is a still a work-in-progress.

from Tkinter import *
import time

master = Tk()

n = int(0)
inc = int(1)
money = int(0)
autoclick = int(0)

def deduction(): # 1 autoclick is $20, deductions

    global money, autoclick

    money = money - 20
    autoclick = autoclick + 1
    automoney()

def automoney(): # Increases money every second

    global money, autoclick

    money = money + autoclick
    print("+" + str(autoclick) + " money!")
    time.sleep(1)
    automoney()

def printmoney(): # Checks how much money you have

    print('Your balance is ' + str(money) + ' dollars.')

def collectmoney(): # Increases money every click

    global n, inc, money

    n = n + inc
    print('+' + str(n) + ' money!')
    money = money + n
    n = n - inc

def checkauto(): # Checks how much Auto-Clickers you have

    global autoclick

    print('You have ' + str(autoclick) + ' Auto Clickers.')

button1 = Button(master, text='Cash!', command=collectmoney)
button1.pack()

checkbutton1 = Button(master, text='Check Cash', command=printmoney)
checkbutton1.pack()

incbutton1 = Button(master, text='Auto Clicker', command=deduction)
incbutton1.pack()

checkbutton2 = Button(master, text='Check Auto Clickers', command=checkauto)
checkbutton2.pack()

mainloop()

... it works, but Tkinter crashes when I press the button Auto Clicker (probably due to the infinite loop).

I followed the instructions in this, and changed some of the code to this:

def automoney():

    money.set(money.get() + autoinc.get())
    incbutton1.after(1000, automoney)

incbutton1.after(1000, automoney)
incbutton1.mainloop()

... which didn't work.

Is there any way to fix the button crashing, while still doing everything it's meant to do?

Community
  • 1
  • 1
Qwerp-Derp
  • 487
  • 7
  • 20

1 Answers1

1

With time.sleep, Tkinter does not crash, but the button does never "finish", and thus the UI remains unresponsive. Using after is correct, you just have to remove those two lines:

incbutton1.after(1000, automoney)
incbutton1.mainloop()

You do not need those, as the automoney function will be called when the button is clicked.

Also, you might want to change your deduction function so it does not call the automoney function again, if it is already running, but just increases the autoclick increment.

def deduction(): # 1 autoclick is $20, deductions
    global money, autoclick
    money = money - 20
    autoclick = autoclick + 1
    if autoclick == 1: # only start the first time
        automoney()

def automoney():
    global money, autoclick
    money = money + autoclick
    print("+" + str(autoclick) + " money!")
    master.after(1000, automoney)
tobias_k
  • 81,265
  • 12
  • 120
  • 179