[英]How to Avoid Blocking tkinter GUI while an infinite loop is running?
我制作了以下程序來根據一天中的時間更改屏幕亮度。 它使用無限循環來不斷檢查時間,但這也阻止用戶更改 tkinter window 中的值或關閉它。 有沒有辦法避免這種情況?
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()
您必須在while
循環中的任何位置添加<tk.Tk object>.update()
,如下所示:
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="This is a button")
button.pack()
while True:
root.update()
root.update()
更新 tcl 並停止“程序沒有響應”消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.