无限循环崩溃Tkinter

时间:2015-08-12 08:44:00

标签: python tkinter

我正在使用Python制作增量游戏(例如Cookie Clicker风格的游戏),这仍然是一项正在进行的工作。

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()

......它有效,但当我按下Auto Clicker按钮时Tkinter崩溃(可能是由于无限循环)。

我按照this中的说明操作,并将部分代码更改为:

def automoney():

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

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

......没有用。

有没有什么方法可以解决按钮崩溃问题,同时仍然可以完成它的所有工作?

1 个答案:

答案 0 :(得分:1)

使用time.sleep,Tkinter不会崩溃,但按钮永远不会完成",因此UI仍然没有响应。使用after是正确的,您只需删除这两行:

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

您不需要这些,因为单击按钮时将调用automoney函数。

此外,您可能希望更改deduction函数,以便它不会再次调用automoney函数(如果它已在运行),只是增加autoclick增量。

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)