Why cant python gui modules handle while true loops is it a python problem or a module problem?

huangapple go评论51阅读模式
英文:

Why cant python gui modules handle while true loops is it a python problem or a module problem?

问题

在创建Python项目时,我想要创建一个GUI,所以我决定使用tkinter模块。在尝试在我的代码中实现一个while True循环后,似乎GUI已经冻结并且无法使用,所以我在这里问一下,这是GUI模块本身的问题,还是Python本身的问题?在其他编程语言中是否也有相同的情况?

英文:

Whilst creating a project in python, I wanted to create a GUI, so I decided, to use the module tkinter. After trying to implement a while True loop in my code, it seems the GUI had frozen and was unusable, so I am here to ask is this a problem with the GUI modules themselves, or is it a problem with Python itself? Is this the same in other languages?

答案1

得分: 1

这是大多数GUI框架的本质。要使GUI正常工作,它必须能够接收持续的事件流以进行处理。这些事件可以是按钮点击、键盘上的输入以及操作系统生成的事件,操作系统告诉窗口需要刷新。

处理这些事件的代码通常称为事件循环 - 它是一个全局循环,等待事件,将它们与已注册的处理程序进行比较,然后调用处理程序。在tkinter中,调用mainloop函数启动了这个事件循环。

当您将长时间运行或无限循环放在与GUI运行的同一线程中时,当该代码正在运行时,GUI框架无法处理这些事件。因此,GUI似乎被冻结,因为它无法自行刷新。

一些工具包可能在单独的线程中运行事件循环。这不适用于tkinter,也许其他基于Python的GUI框架也是如此。在tkinter中,在某些平台上,最好在创建小部件的同一线程中运行事件循环。在OSX上,这是一个严格的要求。

如果您需要在GUI程序中创建自己的循环,或者需要运行长时间的函数,最好为任何这样的代码创建一个单独的线程。

英文:

It is the nature of most GUI frameworks. For a GUI to work, it must be able to receive a steady flow of events to be processed. These events can be button clicks, typing on a keyboard, and system-generated events where the OS tells the window it needs to be refreshed.

The code that processes these events is typically called the event loop - it is a global loop that waits for events, compares them to registered handlers, and then calls the handlers. In tkinter, calling the mainloop function starts this event loop.

When you put a long or infinite loop in the same thread that the GUI is operating, while that code is running the GUI framework is unable to process these events. Thus, the GUI appears to be frozen because it can't refresh itself.

Some toolkits might run the event loop in a separate thread. That is not the case with tkinter, and maybe other python-based GUI frameworks. With tkinter, on some platforms it's best to run the event loop in the same thread that created the widgets. On OSX, this is a strict requirement.

If you need to create your own loops in a GUI program, or any long running function, it's best that you create a separate thread for any such code.

huangapple
  • 本文由 发表于 2023年2月19日 11:12:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定