我正在用 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()
...这没用。
有什么方法可以解决按钮崩溃的问题,同时还能按预期执行所有操作吗?
请您参考如下方法:
使用 time.sleep,Tkinter 不会崩溃,但按钮永远不会“完成”,因此 UI 仍然没有响应。使用 after 是正确的,您只需删除这两行:
incbutton1.after(1000, automoney)
incbutton1.mainloop()
您不需要这些,因为单击按钮时将调用 automoney 函数。
此外,您可能想要更改您的deduction 函数,这样它就不会再次调用automoney 函数(如果它已经在运行),而只是增加自动点击增量。
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)
