简体   繁体   中英

Python GUI shuts down when i use infinite loop

I tried to make a Clicker and I used an infinite loop, so I would raise my Variable every second. But every time I use the Button, my program crashes. Do you have any advice how I prevent that, because I have no idea what is really happening.

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

Firstly, in your example bitcoins1 is undeclared. I assume this is just a variable name you forgot to change before posting, so I renamed it to clicks in order to replicate your issue.

Second, you have your Elfhilft() function using sleep() , which is causing issues with your Tkinter app. Tkinter uses its own loop system to handle real-time stuff, and sleep will cause that loop to stall in most cases. I suggest you use an implementation of after ( How to create a timer using tkinter? ) in order to replicate the autoclicker-esque function I assume you're trying to implement. As an example:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM