运行时错误:主线程不在主循环中,使用tkinter.simpledialog时

1 投票
1 回答
3578 浏览
提问于 2025-05-01 15:38

这是我的代码:

import threading
import tkinter.simpledialog

def showDialog(evt):
    dlg = tkinter.simpledialog.SimpleDialog(root,text='Test!', buttons=['OK'])
    dlg.go()

def test():
    threading.Thread(target=root.event_generate, args=('<<showDialog>>',)).start()

root = tkinter.Tk()
root.bind('<<showDialog>>',showDialog)
tkinter.Button(text = 'showDialog',command = test).pack()
root.mainloop()

我用Python3.4运行这段代码

第一次点击显示对话框的按钮时,它运行得很好

但是如果我按下确定,然后再点击这个按钮,就会出现一个运行时错误:

Exception in thread Thread-2:
Traceback (most recent call last):
  File "D:\Program Files\Python34\lib\threading.py", line 921, in _bootstrap_inner
    self.run()
  File "D:\Program Files\Python34\lib\threading.py", line 869, in run
    self._target(*self._args, **self._kwargs)
  File "D:\Program Files\Python34\lib\tkinter\__init__.py", line 1501, in event_generate
    self.tk.call(args)
RuntimeError: main thread is not in main loop

我最近在学习Python,这段代码只是一个示例。我想在按下按钮后在子线程中做一些工作,因为这会花费几秒钟,我不想让用户界面卡住。当工作完成后,它会显示一个对话框。

有人能告诉我怎么用tkinter实现这个功能吗?还有为什么会出现这个问题?

谢谢!抱歉我的英语不好。

暂无标签

1 个回答

0

在使用线程和图形用户界面(GUI),特别是tk时,会遇到一些麻烦。虽然我不清楚所有的规则,但不可预知的错误和死锁是常见的问题。我有点惊讶的是,在主线程和主循环之外的另一个线程中生成事件居然能成功一次。(你为什么要这么做呢?)而在同一个线程中运行的简化函数则能稳定地工作。

def test():
    root.event_generate('<<showDialog>>')

撰写回答