【发布时间】:2015-08-12 08:43:59
【问题描述】:
我正在用 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()
...这不起作用。
有没有什么办法可以修复按钮崩溃的问题,同时还能做它应该做的所有事情?
【问题讨论】:
-
@tobias_k 我试过了,但出现“incbutton1 is not defined”的错误。
-
@tobias_k 等等……它有效! Tkinter 按钮不再崩溃!
-
你不需要最后两行。该函数是通过按钮调用的,您的代码中已经有一个
mainloop。看我的回答。