当我使用无限循环时,Python GUI会关闭

2024-09-30 20:34:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一个Clicker,我使用了一个无限循环,所以我会每秒钟提高一个变量。但每次我用这个按钮,我的程序就会崩溃。 你有什么建议我如何防止,因为我不知道到底发生了什么。你知道吗

import time
from tkinter import *

class Clicker :
    #updates the Label
    def AK_CLabel(self):
        self.ClickerLabel.configure(text="Du hast " + str(self.Clicks))

    #Generates Clicks
    def Klicken(self):
        self.Clicks += 1
        self.AK_CLabel()
    #raises price of Helping Elf and raises the clicks per second
    def HElf(self) :
        if(self.Clicks >= self.priceHElf) :
            self.Clicks -= self.priceHElf
            self.priceHElf = self.priceHElf * 1.2
            self.Elfs += 1
            self.Elfhilft()
            self.AK_CLabel()

    #Should make the Clicks go up by the amount of Elfs, but if I use the Button the Programm shuts down
    def Elfhilft(self):
        while (not time.sleep(5)):
            self.Clicks = self.Bitcoins1 + self.Elfs
            time.sleep(1)

    def __init__(self, master):
        self.master = master
        self.master.title = "Der Klicker"


        self.Elfs = 0
        self.priceHElf = 30
        self.Clicks = 30

        #Buttons and Label
        self.DerKnopf = Button(text = "Clicks", command = self.Klicken)
        self.ClickerLabel = Label(text = "You have " +str(self.Clicks))
        self.HelferElf = Button(text = "A helping Fairy", command = self.HElf)


        self.DerKnopf.pack()
        self.ClickerLabel.pack()
        self.HelferElf.pack()

root = Tk()
my_gui = Clicker(root)
root.mainloop()

Tags: thetextselfmastertimedefbuttonlabel
1条回答
网友
1楼 · 发布于 2024-09-30 20:34:30

首先,在您的示例中bitcoins1是未声明的。我假设这只是一个变量名,您在发布之前忘记更改,所以我将其重命名为clicks,以便复制您的问题。你知道吗

其次,您的Elfhilft()函数使用sleep(),这会导致Tkinter应用程序出现问题。Tkinter使用自己的循环系统来处理实时内容,在大多数情况下,sleep会导致循环停止。我建议您使用afterHow to create a timer using tkinter?)的实现来复制我假设您正在尝试实现的autoclicker-esque函数。例如:

def autoclick(self):
    self.clicks = self.clicks + self.Elfs

#In main app / __init__()
root.after(1000, self.autoclick) # updates auto-clicks every second

相关问题 更多 >