我想制作这个小应用程序,以每1秒更新一次tkinter window中的信息。该应用程序显示计算机信息并生成一个.txt文件,然后将其解析到tkinter窗口中,这是该应用程序的第一个问题,如果我想每隔1秒更新一次tkinter窗口的内容,这将无济于事。还需要先更新.txt文件。
我已经创建了一个类(UpdateTextTkinter),目的是测试是否可以通过按按钮来更新窗口中的文本-我正在考虑每次按下按钮时都使用它来更新内容。
我需要什么帮助或想法:
这里是代码:
# check if file exists, if not create with WRITE flag
path_text = pathlib.Path("path") # path to txt file
if path_text.is_file():
# make file WRITABLE
filename = "path" # path to txt file
os.chmod(filename, S_IWUSR)
else:
# pop-up: file not found and will be created
response = win32ui.MessageBox("File inexistent - will be created", "Exception: File not found", win32con.MB_OKCANCEL)
if response == win32con.IDCANCEL:
# branch to exit execution if CANCEL is pressed
exit()
# branch to continue execution if OK is pressed
elif response == win32con.IDOK:
# file was not found, create it here and apprend it with data (write flag)
f = open("path", "w+") #path to txt file
# covert large numbers of bytes into a defined format (kilo, mega, giga, tera, peta)
def get_size(bytes, suffix="B"):
"""
Scale bytes to proper format:
1253656 -> '1.20MB'
1253656678 -> '1.17GB'
:param bytes:
:param suffix:
:return:
"""
factor = 1024
for unit in ["", "K", "M", "G","T", "P"]:
if bytes < factor:
return f"{bytes:.2f}{unit}{suffix}"
bytes /= factor
# class UpdateTextTkinter:
# def __init__(self):
# self.root = tk.Tk()
# self.text = tk.StringVar()
# # pass object to be updated
# self.text.set("Test")
# self.label = tk.Label(self.root, textvariable=self.text)
#
# self.button = tk.Button(self.root,
# text = "UPDATE",
# command = self.changeText)
# self.button.pack()
# self.label.pack()
# self.root.mainloop()
#
# # define changeText function and pass object to be updated
#
# def changeText(self):
# self.text.set("Test u")
#
#
# app = UpdateTextTkinter()
# Reminder
print("="*40, "REMINDER", "="*40, file = f)
now_time = datetime.now()
current_time = now_time.strftime("%H:%M:%S")
print(f"Keep in mind that this is not updating live, it's just a snapshot of the system at a certain time({current_time})!", file = f)
# Sys info
print("\n", "="*40, "System Information", "="*40, file = f)
uname = platform.uname()
print(f"System: {uname.system}", file = f)
print(f"Node Name: {uname.node}", file = f)
print(f"Release: {uname.release}", file = f)
print(f"Version: {uname.version}", file = f)
print(f"Machine: {uname.machine}", file = f)
print(f"Processor: {uname.processor}", file = f)
# Get boot date and time
print("\n", "="*40, "BOOT Time", "="*40, file = f)
boot_time_timestamp = psutil.boot_time()
bt = datetime.fromtimestamp(boot_time_timestamp)
print(f"Boot date: {bt.day}/{bt.month}/{bt.year}", file = f)
print(f"Boot time: {bt.hour}/{bt.minute}/{bt.second}", file = f)
# CPU info
print("\n", "="*40, "CPU Info", "="*40, file = f)
# Get number of Cores
print("Physical cores: ",psutil.cpu_count(logical=False), file = f)
print("Threads: ",psutil.cpu_count(logical=True), file = f)
# CPU frequencies
cpufrequency = psutil.cpu_freq()
print(f"Mininum frequency: {cpufrequency.min:.2f}MHz", file = f)
print(f"Maximum frequency: {cpufrequency.max:.2f}MHz", file = f)
print(f"Current frequency: {cpufrequency.current:.2f}MHz", file = f)
# CPU usage
print("CPU Usage Per Core:", file = f)
for i, percentage in enumerate(psutil.cpu_percent(percpu = True, interval = 1)):
print(f"Core {i}: {percentage}%", file = f)
print(f"Total CPU Usage: {psutil.cpu_percent()}%", file = f)
# MEM information
print("\n", "="*40, "Memory Information", "="*40, file = f)
# get memory details
svmem = psutil.virtual_memory()
print(f"Total memory: {get_size(svmem.total)}", file = f)
print(f"Available memory: {get_size(svmem.available)}", file = f)
print(f"Used memory: {get_size(svmem.used)}", file = f)
print(f"Percentage memory: {svmem.percent}%", file = f)
# get swap memory (if existent)
swap = psutil.swap_memory()
print(f"Total swap memory: {get_size(swap.total)}", file = f)
print(f"Free swap memory: {get_size(swap.free)}", file = f)
print(f"Used swap memory: {get_size(swap.used)}", file = f)
print(f"Percentage swap memory: {swap.percent}%", file = f)
# DISK usage
print("\n", "="*40, "Disk Information", "="*40, file = f)
print("Partitions and usage:", file = f)
# get all disk partitions
partitions = psutil.disk_partitions()
for partitions in partitions:
print(f"\nDevice: {partitions.device}", file = f)
print(f"Mountpoint: {partitions.mountpoint}", file = f)
print(f"File sys type: {partitions.fstype}", file = f)
try:
partitions_usage = psutil.disk_usage(partitions.mountpoint)
except PermissionError:
# can't be catched due to disk that isn't ready
continue
print(f"Total size: {get_size(partitions_usage.total)}", file = f)
print(f"Used space: {get_size(partitions_usage.used)}", file = f)
print(f"Free space: {get_size(partitions_usage.free)}", file = f)
print(f"Percentage size: {partitions_usage.percent}%", file = f)
# get IO statistics since boot
disk_io = psutil.disk_io_counters()
print(f"Total read: {get_size(disk_io.read_bytes)}", file = f)
print(f"Total write: {get_size(disk_io.write_bytes)}", file = f)
# Network information
print("\n", "="*40, "Network Information", "="*40, file = f)
# get all network interfaces (virtual and physical)
if_addrs = psutil.net_if_addrs()
for interface_name, interface_addresses in if_addrs.items():
for address in interface_addresses:
print(f"=== Interface: {interface_name} ===", file = f)
if str(address.family) == 'AddressFamily.AF_INET':
print(f" IP Address: {address.address}", file = f)
print(f" Netmask: {address.netmask}", file = f)
print(f" Broadcast IP: {address.broadcast}", file = f)
elif str(address.family) == 'AddressFamily.AF_PACKET':
print(f" MAC Address: {address.address}", file = f)
print(f" Netmask: {address.netmask}", file = f)
print(f" Broadcast MAC: {address.broadcast}", file = f)
# get IO statistics since boot
net_io = psutil.net_io_counters()
print(f"Total Bytes Sent: {get_size(net_io.bytes_sent)}", file = f)
print(f"Total Bytes Received: {get_size(net_io.bytes_recv)}", file = f)
# Make file READ-ONLY
# filename = "path" #path to txt file
# os.chmod(filename, S_IREAD)
#Close file
f.close()
# Import text file and parse it into a tkinter GUI
# filepath = "path" #path to txt file
root = Tk()
root.title("Computer Informations")
root.iconbitmap("C:\\Users\\User\\PycharmProjects\\FirstSteps\\Computer_info\\iconbitmap")
# open file as in Tkinter (read-only)
with open("path", "r") as f: # path to txt file
# display file in a tkinter window
Label(root, text=f.read()).pack()
root.mainloop()
# Delete file after is parsed in Tkinter
if os.path.exists("path"): # path to txt file
os.remove("path") # path to txt file
else:
# create message box error: file not found, cannot be deleted
exit_response = win32ui.MessageBox("File inexistent - program will exit", "Exception: File not found", win32con.MB_OK)
# branch to continue exectuion if OK is pressed
if exit_response == win32con.IDOK:
exit()
PS:用于显示sys-info的代码来自互联网,我正试图通过使用它来学习更多Python!
谢谢!
为了每隔一段时间更新窗口,可以使用如下线程:
from threading import Thread
from time import sleep
def update():
while True:
# do what you want to update here
sleep(1)
# and to start the thread, just do
Thread(target=update).start()
并且使用此更新代码
from threading import Thread
from time import sleep
import tkinter as tk
w = tk.Tk()
lbl = tk.Label(w, text="HELLO")
def update():
while True:
# update stuff
lbl.config(text=result)
sleep(1)
# and to start the thread, just do
Thread(target=update).start()
感谢Amin说如何使用线程顺便说一句