Uni*_*ewb 1 python multithreading schedule tkinter python-multithreading
好吧,我是 python 的新手,我很难在 Tkinter 中创建线程,正如你们都知道在 Tkinter 中使用 while 会使它没有响应并且脚本仍在运行。
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()
Run Code Online (Sandbox Code Playgroud)
我尝试过做类似的事情,但它仍然使 tkinter 没有响应,提前致谢。
正如评论中提到的,在大多数情况下,您不需要线程来运行“假”while 循环。您可以使用该after()方法来安排您的操作,使用tkinter'smainloop作为“衣帽架”来安排事情,就像在 while 循环中一样。
这适用于您可以简单地抛出命令的所有情况,例如subprocess.Popen()更新小部件、显示消息等。
当计划的进程在主循环内运行需要花费大量时间时,它不起作用。因此,这是一个无赖;它只会保存.time.sleep()mainloop
然而,在该限制内,您可以运行复杂的任务、计划操作甚至设置break(等效)条件。
只需创建一个函数,然后使用 启动它window.after(0, <function>)。在函数内部,(重新)使用 安排函数window.after(<time_in_milliseconds>, <function>)。
要应用类似于中断的条件,只需路由该进程(在函数内部)即可不再被调度。
用一个简化的例子可以很好地说明这一点:
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()
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,我们运行计划进程十五秒。当循环运行时,函数 会及时执行几个简单的任务fakewhile()。
在这十五秒之后,我们可以重新开始或“休息”。只需取消注释指定的部分即可查看...
| 归档时间: |
|
| 查看次数: |
2107 次 |
| 最近记录: |