gpt4 book ai didi

python - Tkinter 消息框在按下“确定/确认”后不会消失

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:56 24 4
gpt4 key购买 nike

我写了一个小脚本来跟踪我设备的电池容量。主要用于学习 Python。

我决定使用循环来识别低容量。到目前为止没问题,但是当我使用 tkinter messagebox 时,在我确认警告后窗口不会消失。

import os
from time import sleep
import tkinter as tk
from tkinter import *
from tkinter import messagebox

stat = "/sys_vars/status"
plugged = "PLUGGED"
unplugged = "UNPLUGGED"
batfile = "/sys_vars/capa"

root = tk.Tk()
root.withdraw()

def read(sysfile):
with open(sysfile, "r") as f:
return f.read()

def loopcheck():
plug = str(read(stat).strip())
bat = int(read(batfile))
if plug == plugged:
sleep(2)
if plug == unplugged and 6 <= bat <= 15:
messagebox.showwarning("Alert!","Battery Low!\nCharging Required!")
sleep(2)
if plug == unplugged and bat <= 5:
messagebox.showwarning("ALERT!","Battery ULTRA Low!\nCharging Required!")
sleep(2)

if __name__ == "__main__":
messagebox.showinfo("Running!","Battry Status Tracker is now running on machine")
while True:
loopcheck()

我希望我确认警告,然后在几秒后显示消息。

示例中的变量和短 sleep 定时器用于测试。

最佳答案

您应该使用 root.after(2000, loopcheck) 来延迟运行函数,而不是 while Truesleep(2)。它不会阻塞 root.mainloop(),它必须一直运行以从系统获取键/鼠标事件,将事件发送到小部件并重绘窗口/小部件。

我没有这些 /sys_vars 来测试它,但它可能是这样的:

import tkinter as tk 
from tkinter import messagebox

stat = "/sys_vars/status"
plugged = "PLUGGED"
unplugged = "UNPLUGGED"
batfile = "/sys_vars/capa"

def read(sysfile):
with open(sysfile, "r") as f:
return f.read()

def loopcheck():
plug = str(read(stat).strip())
bat = int(read(batfile))

if plug == unplugged:
if 6 <= bat <= 15:
messagebox.showwarning("Alert!","Battery Low!\nCharging Required!")
elif bat <= 5:
messagebox.showwarning("ALERT!","Battery ULTRA Low!\nCharging Required!")

root.after(2000, loopcheck)

if __name__ == "__main__":

root = tk.Tk()
root.withdraw()

messagebox.showinfo("Running!","Battry Status Tracker is now running on machine")
root.after(2000, loopcheck)

root.mainloop()

关于python - Tkinter 消息框在按下“确定/确认”后不会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58650880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com