【问题标题】:How to loop this code?如何循环这段代码?
【发布时间】:2016-05-14 18:34:51
【问题描述】:

我试图循环这个但每次都失败。 这是我尝试循环的 def create_widgets。所以我得到了一个 GUI,它会在某些东西下线时显示一个红色按钮/框。

这是我尝试使用的代码。

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

【问题讨论】:

  • 你想让整个函数在第一次执行时循环吗?
  • 在不相关的说明中,您通常不希望在程序开始之外的任何地方导入模块。
  • 我的回答有帮助吗?如果没有,请告诉我,以便我进行编辑。
  • 它是如何失败的?它有什么作用,与您的预期有何不同?
  • @BryanOakley 你来晚了,布莱恩。

标签: python-3.x tkinter


【解决方案1】:

您可以使用Tkafter 方法将其附加到Tk 的事件循环中。

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"

然后,这条线在app = Application(root)root.mainloop() 之间的任意位置:

root.after(0, app.if_offline)

after 将一个进程附加到Tk 事件循环上。第一个参数是以毫秒为单位重复该过程的频率,第二个参数是要执行的函数对象。由于我们指定的时间为0,它会不断检查并不断更新按钮的背景颜色。如果这会搅动您的 CPU,或者您不想 ping 那么多,您可以将重复时间更改为更大的值。

传入的函数对象应该就是这样:一个函数对象。它与Button 构造函数中的命令参数具有相同的规则。 如果您需要将参数传递给函数,请使用像这样的 lambda:

root.after(0, lambda: function(argument))

这是因为 lambda 函数返回一个函数对象,该对象在执行时会运行 function(argument)

Source

【讨论】:

  • 嗨,我是编程新手,所以我真的不明白为什么我在写这篇文章时会出错。 NameError: name 'root' is not defined root.after(0, if_offline) root.mainloop()
  • 尝试为类中的所有内容添加一个缩进。
  • 我的错误。它必须是app.if_offline 而不是if_offline。我编辑了答案以包含它。
  • 我现在没有错误,但它仍然循环。 'def if_offline(self):' import os #Router Ping hostname = "182.83.0.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.after( 0,if_offline) root.mainloop()
  • @user6335058 我不确定您的具体示例。它可能还有其他与循环无关的问题,但这些是你自己去寻找的。我能告诉你的是,使用after 会将某个函数附加到Tk 事件循环中,并且它会一遍又一遍地重复,具体取决于您提供给after 的第一个参数。
猜你喜欢
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多