【问题标题】:Tkinter GUI only updates when mouse is movedTkinter GUI 仅在鼠标移动时更新
【发布时间】:2012-08-02 23:34:22
【问题描述】:

我正在运行一个 Tkinter GUI,它使用 subprocess.Popen(...) 启动另一个进程(python 脚本),并使用管道用于 stdout 和 stderr。然后我将分离一个单独的线程以异步读取该进程的输出/错误,并使用threading.Thread 将其绘制到 Tkinter Text 小部件中。

除了异步之外,一切都很好。读取线程仅在我移动鼠标或按下键盘上的键时执行。我什至将打印语句放入线程函数中,当我在圆圈中移动鼠标时它们开始/停止打印。

这是我正在使用的异步读取类,借用自 here

class AsynchronousFileReader(threading.Thread):
    '''
    Helper class to implement asynchronous reading of a file
    in a separate thread. Pushes read lines on a queue to
    be consumed in another thread.
    '''

    def __init__(self, fd, queue):
        assert isinstance(queue, Queue.Queue)
        assert callable(fd.readline)
        threading.Thread.__init__(self)
        self._fd = fd
        self._queue = queue

    def run(self):
        '''The body of the tread: read lines and put them on the queue.'''
        for line in iter(self._fd.readline, ''):
            self._queue.put(line)

    def eof(self):
        '''Check whether there is no more content to expect.'''
        return not self.is_alive() and self._queue.empty()

还有我从异步文件阅读器中提取消息的消耗方法(这是在单独的线程上运行的方法:

def consume(self, process, console_frame):
    # Launch the asynchronous readers of the process' stdout and stderr.

    stdout_queue = Queue.Queue()
    stdout_reader = AsynchronousFileReader(process.stdout, stdout_queue)
    stdout_reader.start()
    stderr_queue = Queue.Queue()
    stderr_reader = AsynchronousFileReader(process.stderr, stderr_queue)
    stderr_reader.start()

    # Check the queues if we received some output (until there is nothing more to get).
    while not stdout_reader.eof() or not stderr_reader.eof():
        # Show what we received from standard output.
        while not stdout_queue.empty():
            line = stdout_queue.get()
            console_frame.writeToLog(line.strip(), max_lines=None)
            time.sleep(.03) # prevents it from printing out in large blocks at a time

        # Show what we received from standard error.
        while not stderr_queue.empty():
            line = stderr_queue.get()
            console_frame.writeToLog(line.strip(), max_lines=None)
            time.sleep(.03) # prevents it from printing out in large blocks at a time

        # Sleep a bit before asking the readers again.
        time.sleep(.05)

    # Let's be tidy and join the threads we've started.
    stdout_reader.join()
    stderr_reader.join()

    # Close subprocess' file descriptors.
    process.stdout.close()
    process.stderr.close()

    print "finished executing"
    if self.stop_callback:
        self.stop_callback()

就像我之前说的——consume() 线程仅在我移动鼠标或在键盘上键入时执行——这意味着 writeToLog(...) 函数(用于将文本附加到 Tkinter GUI)仅在鼠标/发生键盘活动...有什么想法吗?

编辑:我想我可能知道发生了什么......如果我评论 writeToLog(...) 调用并将其替换为简单的打印(将 Tkinter 排除在等式之外),那么消费线程正常执行。看来 Tkinter 是这里的问题。关于我可以从消费线程完成 Tkinter 文本小部件更新的任何想法?

EDIT2:感谢 cmets,它可以正常工作。这是我使用的最终代码:

gui_text_queue = Queue.Queue()


def consume(self, process, console_frame):
    # Launch the asynchronous readers of the process' stdout and stderr.

    stdout_queue = Queue.Queue()
    stdout_reader = AsynchronousFileReader(process.stdout, stdout_queue)
    stdout_reader.start()
    stderr_queue = Queue.Queue()
    stderr_reader = AsynchronousFileReader(process.stderr, stderr_queue)
    stderr_reader.start()

    # Check the queues if we received some output (until there is nothing more to get).
    while not stdout_reader.eof() or not stderr_reader.eof():
        # Show what we received from standard output.
        while not stdout_queue.empty():
            line = stdout_queue.get()
            gui_text_queue.put(line.strip())

        # Show what we received from standard error.
        while not stderr_queue.empty():
            line = stderr_queue.get()
            gui_text_queue.put(line.strip())

        # Sleep a bit before asking the readers again.
        time.sleep(.01)

    # Let's be tidy and join the threads we've started.
    stdout_reader.join()
    stderr_reader.join()

    # Close subprocess' file descriptors.
    process.stdout.close()
    process.stderr.close()

    if self.stop_callback:
        self.stop_callback()

将此方法添加到我的 Tkinter 控制台框架中,并在框架初始化程序结束时调用它一次:

def pull_text_and_update_gui(self):
    while not gui_text_queue.empty():
        text = gui_text_queue.get()
        self.writeToLog(text, max_lines=None)
    self.after(5, self.pull_text_and_update_gui)

【问题讨论】:

  • 你是怎么调用consume方法的?您将其称为线程。它在另一个线程中启动?
  • t = 线程(target=self.consume, args=[proc, console_frame]); t.start()
  • 我必须在另一个线程中启动 consume() 否则它会挂起 GUI。
  • 我认为从线程写入 gui 元素不安全

标签: python multithreading tkinter


【解决方案1】:

Tkinter 不是线程安全的。如果您的writeToLog 函数试图将数据插入到文本小部件中,您将得到不可预知的行为。为了让单独的线程将数据发送到小部件,您需要将数据写入线程安全队列,然后让主线程轮询该队列(使用 tkinter 的 after 方法)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 2014-06-03
  • 1970-01-01
  • 2023-03-20
  • 2016-05-20
  • 2021-03-25
相关资源
最近更新 更多