simple tkinter battery monitor

leonix.power at gmail.com leonix.power at gmail.com
Sun Jan 27 23:59:20 CET 2013


I tried to write a simple battery monitor for laptops which shows normally just the battery percentage, and when is clicked some more info.
If I click just one time it works, but if I click a second time, the additional info Label seems to be empty (but it holds the dimension of the StringVar content, even if it isn't displayed)
Where am I wrong?
---------------------------------------------------
#!/usr/bin/python3.2

from re import findall, search
from threading import Thread
from time import sleep
from subprocess import Popen, call, PIPE, STDOUT
from tkinter import *



class battery_monitor:

        def __init__(self):
                root=Tk()
#                root.geometry("-0+0")
                root.overrideredirect(True)
                root.wm_attributes("-topmost", 1)
                self.battery_string=StringVar()
                self.battery_percent=StringVar()
                self.battery_label=Label(root, extvariable=self.battery_string, font=("fixed", 9))
                self.battery_icon=Label(root, textvariable=self.battery_percent, font=("fixed", 9), width=3)
                self.battery_icon.grid()
                t=Thread(target=self.update_battery_level_loop)
                t.start()
                root.bind("<Button-1>", self.display_details)
                self.root=root
                root.mainloop()
        
        # displays a message about details of battery status
        # i.e. "on-line" or "charging, 20 min left" and so on
        def display_details(self, event):
                self.battery_icon.grid_remove()
                self.battery_label.grid()
                self.root.update_idletasks()
                sleep(1)
                self.battery_label.grid_remove()
                self.battery_icon.grid()
                self.root.update_idletasks()
        
        # dummy function used just to test the GUI
        def read_battery_level(self):
                self.level=100
                return "battery is full"
        
        # threaded function, should constantly update the battery level
        def update_battery_level_loop(self):
                self.read_battery_level()
                while True:
                        self.battery_percent.set(self.level)
                        self.battery_string.set(self.read_battery_level())
                        sleep(5)





##############################################
#
# main

battery_monitor()



More information about the Python-list mailing list