【问题标题】:Infinite loop crashes Tkinter无限循环使 Tkinter 崩溃
【发布时间】: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。看我的回答。

标签: python tkinter


【解决方案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)

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 1970-01-01
    • 2014-01-31
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多