Python Forum
[Tkinter] Background inactivity timer when tkinter window is not active
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Background inactivity timer when tkinter window is not active
#2
This works fine for me.
import tkinter as tk
from ctypes import Structure, windll, c_uint, sizeof, byref

class LASTINPUTINFO(Structure):
    _fields_ = [
        ('cbSize', c_uint),
        ('dwTime', c_uint),
    ]

def get_idle_duration():
    lastInputInfo = LASTINPUTINFO()
    lastInputInfo.cbSize = sizeof(lastInputInfo)
    windll.user32.GetLastInputInfo(byref(lastInputInfo))
    count = windll.kernel32.GetTickCount()
    return (count - lastInputInfo.dwTime) / 1000.0

class Window(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.counter = tk.IntVar(self, 0)
        self.timer = tk.DoubleVar(self, 0.0)
        tk.Label(self, textvariable=self.counter, width=20).pack(padx=10, pady=10)
        tk.Button(self, text="Iconify", command=self.iconify).pack(padx=10, pady=10)
        self.update()

    def update(self):
        self.counter.set(self.counter.get() + 1)
        if get_idle_duration() > 10.0:
            print("Time to wake up!")
            self.deiconify()
        self.after(1000, self.update)

Window().mainloop()
It also works if the Iconify button calls withdraw() instead of iconify().
Reply


Messages In This Thread
RE: Background inactivity timer when tkinter window is not active - by deanhystad - Apr-14-2022, 08:00 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Tkinter multiple windows in the same window hosierycouch 1 294 May-30-2024, 04:28 AM
Last Post: deanhystad
  Interaction between Matplotlib window, Python prompt and TKinter window NorbertMoussy 3 1,024 Mar-17-2024, 09:37 AM
Last Post: deanhystad
  Transparent window background, but not text on it muzicman0 7 3,424 Feb-02-2024, 01:28 AM
Last Post: Joically
  Tkinter multiple windows in the same window tomro91 1 1,121 Oct-30-2023, 02:59 PM
Last Post: Larz60+
  Centering and adding a push button to a grid window, TKinter Edward_ 15 6,277 May-25-2023, 07:37 PM
Last Post: deanhystad
  My Background Image Is Not Appearing (Python Tkinter) HailyMary 2 5,282 Mar-14-2023, 06:13 PM
Last Post: deanhystad
  [Tkinter] Open tkinter colorchooser at toplevel (so I can select/focus on either window) tabreturn 4 2,184 Jul-06-2022, 01:03 PM
Last Post: deanhystad
  why my list changes to a string as I move to another window in tkinter? pymn 4 2,745 Feb-17-2022, 07:02 AM
Last Post: pymn
  [Tkinter] Not able to get image as background in a Toplevel window finndude 4 4,174 Jan-07-2022, 10:10 PM
Last Post: finndude
  [Tkinter] Tkinter Window Has no Title Bar gw1500se 4 3,048 Nov-07-2021, 05:14 PM
Last Post: gw1500se

Forum Jump:

User Panel Messages

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