简体   繁体   中英

python tkinter menu refresh

I have created a script that connects to my homemade nas with ssh and showing the size, used and available of the hdd in a menu by sending a command and printing it:

import sys, paramiko
from tkinter import *
import os
import tkinter as tk

username = "user"
hostname = "ip"
password = "pass"
command = "df /dev/sda3 -h"
port = 22

try:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    client.connect(hostname, port=port, username=username, password=password)
    stdin, stdout, stderr = client.exec_command(command)
    output = stdout.read()
    root = Tk() 
    root.minsize(width=425, height=200)
    root.maxsize(width=425, height=200)
    root.configure(background='blue')
    menubar = Menu(root)
    root.title("NAS storage")
    msg = tk.Message(root, text = ("size", output[65:69], "used", output[72:75], "available", output[77:81])) #should output hdd info (size, used, avalable)
    msg.config(bg='lightgreen', font=('times', 50, 'italic'))
    msg.pack()
    tk.mainloop()
    root.config(menu=menubar)
    root.mainloop()
finally:
    client.close()

It works but I want to have it refreshed every 5 seconds.

There's no need to constantly refresh the menu. You can specify a command to run immediately before the menu is displayed with the postcommand option.

Here is a contrived example that uses the current time as an item on the menu. Every time you show the menu it will show a new time.

import tkinter as tk
import time

def updateTimeMenu():
    time_menu.delete(0, "end")
    time_menu.add_command(label=time.ctime())

root = tk.Tk()
root.geometry("400x200")

menubar = tk.Menu(root)
root.configure(menu=menubar)

time_menu = tk.Menu(menubar, postcommand=updateTimeMenu,
                       tearoff=False)
menubar.add_cascade(label="Time", menu=time_menu)

root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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