简体   繁体   English

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

[英]Tkinter messagebox doesnt disappear after press 'ok/confirmation

I wrote a little script to track the battery capacity of my device.我写了一个小脚本来跟踪我设备的电池容量。 Mostly for learning Python.主要用于学习 Python。

I decided to use a loop to recognize low capacity.我决定使用循环来识别低容量。 So far it is okay, but when I use a tkinter messagebox , the window does not disappear after I confirm the warning.到目前为止还可以,但是当我使用tkinter messagebox时,在我确认警告后 window 不会消失。

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()

I expect that I confirm the warning and then the message show after the amount of seconds.我希望我确认警告,然后在几秒钟后显示消息。

The variables and the short sleep-timer in the example are there for tests.示例中的变量和短睡眠定时器用于测试。

Instead of while True and sleep(2) you should use root.after(2000, loopcheck) to run function in delay.而不是while Truesleep(2)你应该使用root.after(2000, loopcheck)来延迟运行 function 。 It will not block root.mainloop() which has to run all time to get key/mouse events from system, send events to widgets and redraw windows/widgets.它不会阻止root.mainloop() ,它必须一直运行才能从系统获取键/鼠标事件,将事件发送到小部件并重绘窗口/小部件。

I don't have these /sys_vars to test it but it could be something like this:我没有这些/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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM