【问题标题】:how to run two functions at the same time using tkinter如何使用 tkinter 同时运行两个函数
【发布时间】:2021-06-27 09:26:48
【问题描述】:

所以基本上我想要做的是,当我点击第一个按钮时,程序将每隔一秒继续打印 hello world,直到点击第二个按钮。

这就是我所做的:

import concurrent.futures
import time
import tkinter as tk

call=""
def on_click1():
    while call!="stop":
        print("hello")
        time.sleep(1)

def on_click2():
    call="stop"

root=tk.Tk()
root.title("test")
with concurrent.futures.ProcessPoolExecutor() as executor:
    if __name__ == '__main__':
        btn1=tk.Button(root,text="button1",command=on_click1)
        btn2=tk.Button(root,text="button1",command=on_click2)
        btn1.pack()
        btn2.pack()
        root.mainloop()

但发生的情况是,当我单击第一个按钮时,tkinter 窗口/gui 冻结并且不允许我单击第二个窗口

【问题讨论】:

  • 第一件事是call 不是全局含义您将在函数中本地更改这些变量,而且似乎您不会以任何方式分离这些函数,它们仍在运行相同的线程或某事,无论我如何认为print 这样的功能可以使用.after() 循环轻松处理
  • 尝试在 SO 中搜索 tkintersleepafter。这个问题有很多答案。
  • SO 是什么意思?
  • Stackoverflow, sleep 停止运行 tkinter 主循环。
  • 关于在这个网站上显示计时器或时钟的问题肯定有几十个。

标签: python tkinter


【解决方案1】:

一般不推荐使用带睡眠功能的while循环,而是在tkinter中使用.after()函数。

import concurrent.futures
import tkinter as tk

def on_click1():
    global call                         #if not global, then this call variable will be treated as local
    print("hello")
    call = root.after(1000, on_click1)     #every 1s on_click1 function is called

def on_click2():
    global call                         #if not global, then this call variable will be treated as local
    if call is not None:
        root.after_cancel(call)         #cancels the ongoing root.after() if it exists
        call = None

root=tk.Tk()
root.title("test")
with concurrent.futures.ProcessPoolExecutor() as executor:
    if __name__ == '__main__':
        btn1=tk.Button(root,text="button1",command=on_click1)
        btn2=tk.Button(root,text="button2",command=on_click2)
        btn1.pack()
        btn2.pack()
        root.mainloop()

【讨论】:

  • 单击第二个按钮后如何重新启动 hello 循环?
  • 用您的问题的解决方案编辑了我的代码
猜你喜欢
  • 1970-01-01
  • 2021-07-20
  • 2017-07-26
  • 1970-01-01
  • 2016-05-25
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多