如何在没有GUI冻结的情况下有效地使用tkinter中的调度模块



我是python和tkinter的新手,我制作了一个非常基本的程序,可以在给定的时间范围内检查IP地址ping或可达性。我使用Schedule模块来调度ping,但实际上在单击"启动任务"后,GUI会冻结,而代码仍在后台运行。可能while循环导致了冻结,即使在查看了stackoverflow提到的所有解决方案后,我也未能解决这个问题,因为没有人解决如何在tkinter中完美地使用Schedule模块的问题

我想知道是否有一种方法可以在不使用while循环的情况下实现Schedule模块,或者在不导致GUI冻结的情况下使用while环路。

非常感谢。

我为我目前的案例制作了这个快速样本。

使用Python 3.8.5

目标操作系统:Windows10 pro

在VS代码上测试

import tkinter as tk
import tkinter.font as tkFont
from pythonping import ping
from tkinter import *
from win10toast import ToastNotifier 
import schedule
class App:
def __init__(self, root):

root.title("Ping Check")
width=600
height=400
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
self.ip_address = StringVar()
self.seconds = IntVar()
self.n = ToastNotifier()

IP_Address=tk.Entry(root)
IP_Address["borderwidth"] = "1px"
ft = tkFont.Font(family='Times',size=10)
IP_Address["font"] = ft
IP_Address["fg"] = "#333333"
IP_Address["justify"] = "center"
IP_Address["textvariable"] = self.ip_address
IP_Address.place(x=250,y=70,width=270,height=32)
ip_address_label=tk.Label(root)
ft = tkFont.Font(family='Times',size=10)
ip_address_label["font"] = ft
ip_address_label["fg"] = "#333333"
ip_address_label["justify"] = "center"
ip_address_label["text"] = "Enter IP Address"
ip_address_label.place(x=60,y=70,width=139,height=30)
seconds_label=tk.Label(root)
ft = tkFont.Font(family='Times',size=10)
seconds_label["font"] = ft
seconds_label["fg"] = "#333333"
seconds_label["justify"] = "center"
seconds_label["text"] = "Enter Seconds"
seconds_label.place(x=50,y=170,width=143,height=30)
Seconds=tk.Entry(root)
Seconds["borderwidth"] = "1px"
ft = tkFont.Font(family='Times',size=10)
Seconds["font"] = ft
Seconds["fg"] = "#333333"
Seconds["justify"] = "center"
Seconds["textvariable"] = self.seconds
Seconds.place(x=250,y=170,width=272,height=30)
start_button=tk.Button(root)
start_button["bg"] = "#efefef"
ft = tkFont.Font(family='Times',size=10)
start_button["font"] = ft
start_button["fg"] = "#000000"
start_button["justify"] = "center"
start_button["text"] = "Start Task"
start_button.place(x=100,y=310,width=178,height=30)
start_button["command"] = self.Start_Task
stop_button=tk.Button(root)
stop_button["bg"] = "#efefef"
ft = tkFont.Font(family='Times',size=10)
stop_button["font"] = ft
stop_button["fg"] = "#000000"
stop_button["justify"] = "center"
stop_button["text"] = "Stop Task"
stop_button.place(x=330,y=310,width=172,height=30)
stop_button["command"] = self.Stop_Task
def ping_ip(self):
l = list(ping(self.ip_address.get()))
if not str(l[0]).startswith('Reply'):
self.n.show_toast("Warning!", "Unreachable IP Address, Error Ping Message: Request timed out!")
else:
self.n.show_toast("Successful reply!")
def Start_Task(self):
schedule.every(self.seconds.get()).seconds.do(self.ping_ip)
while True:
schedule.run_pending()
def Stop_Task(self):
schedule.cancel_job(self.Start_Task)
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
root.mainloop()

tkinter这样的GUI工具包是事件驱动的。为了正常工作mainloop必须能够连续处理键盘和鼠标事件。当它不处理事件时,它将启动计划的空闲任务

因此tkinter程序的工作方式与普通Python脚本截然不同。

调用回调以响应激活控件(如单击按钮(。系统在指定的毫秒数后启动空闲任务当系统不忙于处理事件时。您可以安排空闲任务采用CCD_ 4方法。

基本上,回调和空闲任务就是您的程序。但它们是从主循环中的运行的。

因此,无论你在回电中做什么,都不应该花费太长时间。否则,GUI将变得没有响应。因此,在回叫中使用while True不是一个好主意。

在Python 3tkinter程序中,当您想要执行一个长时间运行的任务时,特别是当它涉及磁盘访问或网络活动时,您可能应该在第二个线程中执行。(在Python 3中,tkinter主要是线程安全的。(

编辑1:使用subprocess.Popen异步运行ping程序,而不是使用pythonpingschedule

import subprocess as sp
# class App:
# et cetera...
def query_task(self):
if self.process:
if self.process.returncode:
# The ping has finished
if self.process.returncode != 0:
self.n.show_toast("Warning:", f"ping returned {self.process.returncode}")
else:  # ping has finished successfully.
# self.process.stdout and self.process.stderr contain the output of the ping process...
pass
# So a new task can be started.
self.process = None
else:
# check again after 0,5 seconds.
self.after(0.5, self.query_task);
# By convention, method names should be lower case.
def start_task(self):
if self.process is None:
self.process = sp.Popen(
["ping", self.ip_address.get()], stdout=sp.Pipe, stderr=sp.Pipe
)
# Check after 0.5 seconds if the task has finished.
self.after(0.5, self.query_task);

最新更新