T.Galisnky
T.Galisnky

Reputation: 87

Python3, Tkinter GUI crashes and button remain clicked

I made a code that includes an infinite loop and made a Tkinter interface that has a start button.

When I click the button windows thinks the GUI has crashed -even tho it's working in the background-, and the button remain clicked.

-How do I unclick the button ?

-and how do I make the same Tkinter window start a new loop when clicked again ? making the window stay responsive.

sample code:

import time
from tkinter import *

def do():
    while x > 0:
        try:
            x = 1
            x += 1
            return x
        except:
            time.sleep(x)
            x = 0

window = Tk()

Button(text='Start',width=30, command=do).grid(row=0, column=0)

mainloop()

Where except has an exception error that is deemed to happen,

To add some context I'm using this along with selenium library

Upvotes: 0

Views: 1429

Answers (2)

T.Galisnky
T.Galisnky

Reputation: 87

This worked:

import threading
import time
from tkinter import *

def clicked():
    threading.Thread(target=do).start()

def do():
    while x > 0:
        try:
            x = 1
            x += 1
            return x
        except:
            time.sleep(x)
            x = 0

window = Tk()

Button(text='Start',width=30, command=clicked).grid(row=0, column=0)

mainloop()

Use at your own risk as this by it self won't enable you to break the loop, will update if I found a way

Edit:

Simplest solution is to make daemon thread, this helps close your code if you closed the GUI, you can do this by editing a line from the code above like this:

threading.Thread(target=do, daemon=True).start()

Upvotes: 0

Jebby
Jebby

Reputation: 1955

I see a couple of problems here:

1.) do() is not preceded by def.

2.) expect should be except

3.) Your while loop is blocking the flow of your program. Instead you should use Tk().after(wait_time, method)

With that being said, I'm assuming that you want to count up after the button is pressed.

This starts counting from 0 after the button is clicked. When the button is clicked again, it stops printing count and resets it:

from tkinter import *

class App:

    def __init__(self):
        self.root = Tk()

        self.count = 0
        self.do_count = False

        self.button = Button(self.root, text="Click me.", command=self.do)
        self.button.pack()

        self.root.mainloop()

    def do(self):
        self.do_count = not self.do_count
        if not self.do_count:
            self.count = 0
        self.update()

    def update(self):
        if self.do_count:
            print(self.count)
            self.count += 1
            self.root.after(1000, self.update)


app = App()

Upvotes: 1

Related Questions