Python Forum
[Tkinter] How to deal with code that blocks the mainloop, freezing the gui
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] How to deal with code that blocks the mainloop, freezing the gui
#3
Another example of using after to make a change one minute after clicking a button.

The return of after gives an id that can be used to cancel a call, that way if a button is pressed again before the call is made it will cancel the current one and a new after one minute call can be made.

See the following modified code.
import tkinter as tk
import tkinter.ttk as ttk


class MainFrame(tk.Frame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.process = tk.IntVar(value=5)
        self.after_id = None

        self.progressbar = ttk.Progressbar(
            self.master, length=200, maximum=10, variable=self.process
        )
        self.progressbar.grid(row=1)

        self.add_button = ttk.Button(
            self.master, text="Water +", command=self.add_water
        )
        self.sub_button = ttk.Button(
            self.master, text="Water -", command=self.sub_water
        )

        self.label = ttk.Label(self.master, textvariable=self.process)

        self.label.grid(row=0)
        self.add_button.grid(row=0, sticky="e")
        self.sub_button.grid(row=0, sticky="w")

    def reset_water(self):
        self.process.set(5)
        self.after_id = None

    def reset_after(self, delay_ms):
        if self.after_id:
            self.after_cancel(self.after_id)

        self.after_id = self.after(delay_ms, self.reset_water)

    def add_water(self):
        progress_value = self.process.get()
        if progress_value < self.progressbar["maximum"]:
            self.process.set(progress_value + 1)
            self.reset_after(60000)

    def sub_water(self):
        progress_value = self.process.get()
        if progress_value > 0:
            self.process.set(progress_value - 1)
            self.reset_after(60000)


if __name__ == "__main__":
    tk_app = tk.Tk()
    main_frame = MainFrame()
    tk_app.mainloop()
Reply


Messages In This Thread
RE: How to deal with code that blocks the mainloop, freezing the gui - by Yoriz - May-22-2019, 05:31 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [WxPython] How to deal with code that blocks the mainloop, freezing the gui Yoriz 1 9,640 May-06-2019, 12:17 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020