簡體   English   中英

Tkinter 重疊網格小部件

[英]Tkinter overlapping grid widgets

每個人。 我是 Python 的新手並試圖學習它,因為我未來的工作需要我了解它。 我在玩 Tkinter,試圖讓 ping 腳本工作。 此腳本的結果將顯示第 0 列中的服務器列表和第 1 列中它是向上還是向下的列表。我讓它工作,除了一件事:小部件重疊,導致此腳本成為內存豬。 例如,如果站點“google.com”響應為“UP”而我關閉了我的互聯網,它將顯示為“DOWN”。 但是,只要重新插入我的互聯網,它就會顯示為“UP”,但我可以看到標簽后面的“DOWN”字樣。 在每次使用之前,我嘗試了不同的方法來銷毀小部件,但無法使其正常工作。 我理解我的代碼是否有點亂,所以我絕對願意接受批評。 下面是我在“host”變量中列出的一些示例站點的代碼:

import pyping
import Tkinter as tk
from Tkinter import *
import time

host = ["google.com", "yahoo.com", "espn.com"]

root = tk.Tk()

class PingTest:

    result = []
    resultfc = []

    def __init__(self, hostname, inc):
        self.hostname = hostname
        self.inc = inc
        self.ping(hostname)

    def results(self, result1, resultfc1):
        self.result = result1
        self.resultfc = resultfc1

    def ping(self, y):
        self.y = y
        q = ""
        try:
            x = pyping.ping(self.y, count=1)
            q = x.ret_code
        except Exception:
            pass
        finally:
            if q == 0:
                self.results("UP", "green")
            else:
                self.results("DOWN", "red")

        self.window()

    def window(self):

        self.label1 = Label(root, text=self.hostname)
        self.label2 = Label(root, text=self.result, fg=self.resultfc, bg="black")

        a = Label(root, text=self.hostname)
        b = Label(root, text=self.result, fg=self.resultfc, bg="black")
        b.update()
        b.update_idletasks()
        if b == TRUE:
            b.grid_forget() # These two lines don't seem to help my cause
            b.destroy()
        a.grid(row=self.inc, column=0)
        b.grid(row=self.inc, column=1)


while TRUE:
    i = 0
    for h in host:
        PingTest(h, i)
        i += 1
    time.sleep(1)

我會更新標簽而不是銷毀它們。

我們可以使用線程檢查每個站點而不必阻塞mainloop() 通過創建標簽列表,您可以使用列表的索引在 GUI 上設置標簽,同時我們可以為列表中的每個對象啟動一個線程來檢查站點狀態並返回站點是啟動還是關閉. 我選擇使用urllibthreading來完成這項工作。

import tkinter as tk
import urllib.request
import threading
import time

host = ["google.com", "yahoo.com", "espn.com"]

class CheckURL:
    def __init__(self, host, widget):
        self.host = host
        self.widget = widget
        self.update_labels()

    def update_labels(self):
        if urllib.request.urlopen("http://www." + self.host).getcode() == 200:
            self.widget.config( text='UP', fg='green')
        else:
            self.widget.config(text='DOWN', fg='red')
        time.sleep(5)
        self.update_labels()

root = tk.Tk()
labels = []

for ndex, x in enumerate(host):
    tk.Label(root, text=x).grid(row=ndex, column=0)
    labels.append(tk.Label(root, text='DOWN', fg='red'))
    labels[-1].grid(row=ndex, column=1)
    threading._start_new_thread(CheckURL, (x, labels[-1]))

root.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM