尝试在 python 中使用无限循环进行多线程处理,但我的 GUI 仍然冻结

trying to multi-thread in python with an infinite loop, however my GUI still freezes

所以我对编程非常缺乏经验,但是当我很享受它时,我想我会扩展并尝试一些东西。 我正在尝试编写的程序执行我已经从 tkinter GUI window 中编写的一段代码,并在每天的特定时间设置为 运行,直到程序关闭。 (基本上是一个花哨的警报)。为此,我尝试使用线程模块在后台的不同线程上进行无限 'while' 循环 运行,同时仍然能够将 GUI 用于其他事情。

def continuous_task(args):
    while 0==0:
        currenttime = time.localtime(time.time())
        if currenttime.tm_hour == 8 and currenttime.tm_min == 0 and currenttime.tm_sec == 0:
            task(args)


def background_task(args):
    thread1 = Thread(target = continuous_task(args))
    thread1.start()
    return None

root = Tk()
frame1 = Frame(root)
frame1.pack()
frame2 = Frame(root)
frame2.pack()
frame3 = Frame(root)
frame3.pack()
inputbox = Entry(frame2, width = 20)
inputbox.pack(side = 'left', pady = 10)
header = Label(frame1, text = 'Header', height=3, width = 60)
header.pack(side = 'left')
button = Button(frame2, text = 'Start', width = 10, command = lambda: background_task(inputbox.get()))
button.pack(side = 'left')
Close = Button(frame3, text = 'Close Program', command = root.quit)
Close.pack(side = 'bottom', pady = 5)
root.mainloop()

当我 运行 这段代码时,当我按下开始时 GUI 仍然冻结,并且由于我不完全理解线程模块,所以我在调试这个问题时有点卡住了。

def background_task(entry_value):
    thread1 = Thread(target=continuous_tasks, args=(entry_value,))
    thread1.start()
    return None

典型的未理解 threadingmultiprocessing 库。写target=continous_tasks(args)相当于运行宁continuous_tasks(args)target=None


由于您是编程新手,这里有一些关于您想尝试的技巧。函数continuous_tasks是在特定时间(时分秒)运行的函数。检查模块 schedule,这是正确的方法。

此外,在副线程中进行无限循环绝对不是一个好主意。避免这样做,除非你的线程中有一些中断(比如 threading.{Condition,Event,...}time.sleep),即使你这样做了,你 绝对应该 停下来您的线程中的条件。