Python Tkinter While 线程 [英] Python Tkinter While Thread

查看:47
本文介绍了Python Tkinter While 线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我对 python 有点陌生,我越来越难以在 Tkinter 中创建线程,正如你们都知道的,在 Tkinter 中使用 while 使其无响应并且脚本仍在运行.

Well i am a bit of newb at python, and i am getting hard to make a thread in Tkinter , as you all know using while in Tkinter makes it Not Responding and the script still running.

  def scheduler():
    def wait():
        schedule.run_pending()
        time.sleep(1)
        return
    Hours = ScheduleTest()
    if len(Hours) == 0:
        print("You need to write Hours, Example: 13:30,20:07")
    if len(Hours) > 0:
        print("Scheduled: ", str(Hours))
        if len(Hours) == 1:
            schedule.every().day.at(Hours[0]).do(Jumper)
            print("Will jump 1 time")
        elif len(Hours) == 2:
            schedule.every().day.at(Hours[0]).do(Jumper)
            schedule.every().day.at(Hours[1]).do(Jumper)
            print("Will jump 2 times")
        elif len(Hours) == 3:
            schedule.every().day.at(Hours[0]).do(Jumper)
            schedule.every().day.at(Hours[1]).do(Jumper)
            schedule.every().day.at(Hours[2]).do(Jumper)
            print("Will jump 3 times")
        while True:
            t = threading.Thread(target=wait)
            t.start()
    return
scheduler()

我曾尝试做这样的事情,但它仍然使 tkinter 没有响应提前致谢.

i have tried to do something like this but it still makes tkinter not responding Thanks in advance.

推荐答案

after 方法何时使用;在没有线程的情况下伪造

正如评论中提到的,在大多数情况下,您不需要线程来运行假"程序.while 循环.您可以使用 after() 方法来安排您的操作,使用 tkintermainloop 作为衣帽架"安排事情,就像你在 while 循环中所做的一样.

When to use the after method; faking while without threading

As mentioned in a comment, In far most cases, you do not need threading to run a "fake" while loop. You can use the after() method to schedule your actions, using tkinter's mainloop as a "coat rack" to schedule things, pretty much exactly like you would in a while loop.

这适用于您可以简单地抛出命令的所有情况,例如subprocess.Popen(),更新小部件,显示消息等

This works in all situations where you can simply throw out commands with e.g. subprocess.Popen(), update widgets, show messages etc.

当计划进程花费大量时间时,它不起作用,在主循环运行.因此 time.sleep() 是一个无赖;它只会保存 mainloop.

It does not work when the scheduled process takes a lot of time, running inside the mainloop. Therefore time.sleep() is a bummer; it will simply hold the mainloop.

但是,在该限制内,您可以运行复杂的任务、安排操作甚至设置 break(等效)条件.

Within that limitation however, you can run complicated tasks, schedule actions even set break (-equivalent) conditions.

简单地创建一个函数,用 window.after(0, ) 启动它.在函数内部,(重新)使用 window.after(, ) 调度函数.

Simply create a function, initiate it with window.after(0, <function>). Inside the function, (re-) schedule the function with window.after(<time_in_milliseconds>, <function>).

要应用类似中断的条件,只需路由(在函数内部)不再被调度的进程.

To apply a break- like condition, simply rout the process (inside the function) not to be scheduled again.

最好用一个简化的例子来说明:

This is best illustrated with a simplified example:

from tkinter import *
import time

class TestWhile:
    
    def __init__(self):
        
        self.window = Tk()
        shape = Canvas(width=200, height=0).grid(column=0, row=0)
        self.showtext = Label(text="Wait and see...")
        self.showtext.grid(column=0, row=1)
        fakebutton = Button(
            text="Useless button"
            )
        fakebutton.grid(column=0, row=2)
        
        # initiate fake while
        self.window.after(0, self.fakewhile)
        self.cycles = 0
       
        self.window.minsize(width=200, height=50)
        self.window.title("Test 123(4)")
        self.window.mainloop()

    def fakewhile(self):
        # You can schedule anything in here
        if self.cycles == 5:
            self.showtext.configure(text="Five seconds passed")
        elif self.cycles == 10:
            self.showtext.configure(text="Ten seconds passed...")
        elif self.cycles == 15:
            self.showtext.configure(text="I quit...")
        """
        If the fake while loop should only run a limited number of times,
        add a counter
        """
        self.cycles = self.cycles+1
        """
        Since we do not use while, break will not work, but simply
        "routing" the loop to not being scheduled is equivalent to "break":
        """
        if self.cycles <= 15:
            self.window.after(1000, self.fakewhile)
        else:
            # start over again
            self.cycles = 0
            self.window.after(1000, self.fakewhile)
            # or: fakebreak, in that case, uncomment below and comment out the
            # two lines above
            # pass

TestWhile()

在上面的例子中,我们运行一个预定的进程十五秒.当循环运行时,函数 fakewhile() 会及时执行几个简单的任务.

In the example above, we run a scheduled process for fifteen seconds. While the loop runs, several simple tasks are performed, in time, by the function fakewhile().

在这十五秒后,我们可以重新开始或休息".只需取消对指定部分的注释即可查看...

After these fivteen seconds, we can start over again or "break". Just uncomment the indicated section to see...

这篇关于Python Tkinter While 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆