I have trying to loop this but fail everytime.It´s the def create_widgets I try to loop. So I got a GUI that show a red button/box as soon something goes offline.This is the code I tried to use.from tkinter import *class Application(Frame):""" GUI """def __init__(self, master): """ Initialize the Frame""" Frame.__init__(self,master) self.grid() self.create_widgets()def create_widgets(self): """Create button. """ import os #Router self.button1 = Button(self) self.button1["text"] = "Router" self.button1["fg"] = "white" self.button1.grid(padx=0,pady=5) #Ping hostname = "10.18.18.1" response = os.system("ping -n 1 " + hostname) #response if response == 0: self.button1["bg"] = "green" else: self.button1["bg"] = "red"root = Tk()root.title("monitor")root.geometry("500x500")app = Application(root)root.mainloop() 解决方案 You can attach it onto Tk's event loop using Tk's after method.def if_offline(self): #Ping hostname = "10.18.18.1" response = os.system("ping -n 1 " + hostname) #response if response == 0: self.button1["bg"] = "green" else: self.button1["bg"] = "red"Then, this line goes anywhere between app = Application(root) and root.mainloop():root.after(0, app.if_offline)after attaches a process onto the Tk event loop. The first argument is how often the process should be repeated in milliseconds, and the second is the function object to be executed. Since the time we have specified is 0, it will constantly check and constantly update the button's background color. If that churns your CPU, or you don't want to be pinging that much, you can change the repeat time to something larger.The function object passed in should be just that: a function object. It has the same rules as the command argument in a Button constructor.If you need to pass in arguments to the function, use a lambda like so:root.after(0, lambda: function(argument))This works because the lambda function returns a function object, which when executed will run function(argument).Source 这篇关于如何循环这段代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-19 13:51