如何解决如何在tkinter中有效使用Schedule Module而无需获得GUI Freeze
我是python和tkinter的新手,我制作了非常基本的程序,用于检查给定时间范围内的IP地址ping或可达性。我使用 Schedule模块来调度ping,但实际上在单击Start Task之后,GUI冻结,而代码仍在后台运行。可能是while循环引起了冻结,即使在查看了所有stackoverflow提及的解决方案之后,我也未能解决此问题,因为没有人解决过如何在tkinter中完美使用Schedule模块。
我想知道是否存在一种解决方案,可以在不使用while循环或使用while循环而不导致GUI冻结的情况下实现Schedule模块。
非常感谢您。
我为当前案件做了一个快速的样本。
使用Python 3.8.5
目标操作系统:Windows10专业版
在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,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,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,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()
解决方法
GUI工具箱,例如tkinter
是事件驱动的。为了正常工作,
mainloop
必须能够连续处理键盘和鼠标事件。
当不处理事件时,它将启动计划的空闲任务。
因此tkinter
程序的工作方式与普通的Python脚本完全不同。
调用回调以响应激活控件(例如单击
一个按钮)。
在指定的毫秒数后,系统将启动一个空闲任务
当系统不忙于处理事件时。您可以安排空闲任务
使用Tk.after()
方法。
基本上,回调和空闲任务是您的程序。 但是它们是从在主循环内运行的。。
因此,无论您执行回叫操作,都不会花费太长时间。否则,GUI将无响应。
因此,在回叫中使用while True
并不是一个好主意。
在Python 3 tkinter
程序中,当您想执行长时间运行的任务时,尤其是涉及磁盘访问或网络活动的任务时,您可能应该在第二个线程中执行。 (在Python 3中,tkinter
主要是线程安全的。)
编辑1 :
不用使用pythonping
和schedule
,而是使用subprocess.Popen
异步运行ping
程序:
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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。