如何在tkinter中有效使用Schedule Module而无需获得GUI Freeze

如何解决如何在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 : 不用使用pythonpingschedule,而是使用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 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res