Plazor
Plazor

Reputation: 13

How to Avoid Blocking tkinter GUI while an infinite loop is running?

I made the following program to change screen brightness depending on the time of day. It uses an infinite loop to constantly check the time, but this also prevents the user from changing the values in the tkinter window or from closing it. Is there any way to avoid this?

from datetime import datetime
import screen_brightness_control as sbc
from tkinter import *
m=Tk()
m.title('Brightness Control')
def saver():
    print("Saving")
    global brit
    brit=e3.get()
    global frot
    frot=e1.get()
    global tot
    tot=e2.get()
    a=True
    while a==True:
        current_brightness=sbc.get_brightness()
        now=datetime.now().time()
        if now.hour>int(frot) and now.hour<int(tot) :
            sbc.set_brightness(brit)
        else:
            sbc.set_brightness(40)

Label(m, text='Brightness').grid(row=0,column=0) 
Label(m, text='From').grid(row=1,column=0) 
Label(m, text='To').grid(row=1,column=2) 

e1 = Entry(m)
e2 = Entry(m)
e3 = Entry(m)

e1.grid(row=1, column=1) 
e2.grid(row=1, column=3)
e3.grid(row=0, column=1) 
button = Button(m, text='Save', width=5,command=saver) 
button.grid(row=2,column=3)
m.mainloop()

Upvotes: 1

Views: 2452

Answers (1)

TheLizzard
TheLizzard

Reputation: 7680

You have to add <tk.Tk object>.update() anywhere in your while loop like this:

import tkinter as tk

root = tk.Tk()
button = tk.Button(root, text="This is a button")
button.pack()

while True:
    root.update()

root.update() updates tcl and that stops the "program isn't responding" message.

Upvotes: 2

Related Questions