执行多线程进程
我正在用 python 编写一个简单的聊天客户端代码。我有 GUI,一个用于存储字符串和其他数据的 php 服务器。我想让我的代码能够每 1 秒更新一次聊天(对话文本字段)。 我发布了一些伪代码:
Initialize Gui
Setup Users
UserX write messageX
messageX sent to server
此时,我需要每秒检查 userX(可能是 user1 或 user2)是否有新消息要显示的东西。 如果我输入类似的内容:
while True:
time.sleep(1)
checkAndDisplayNewMessages()
GUI 不会出现!因为在代码末尾我得到了一个 mainloop()
来恢复,我希望我的代码能够为用户提供异步发送和接收消息的可能性!一部分代码用于在用户输入任何消息时发送消息,另一部分在程序运行时不断检查新消息。
I'm writing a code for a simple chat client in python. I have the GUI, a php server to store strings and other data. I want to make my code capable of updating the chat (conversation Text field) each 1 second.
I post a bit of pseudo-code:
Initialize Gui
Setup Users
UserX write messageX
messageX sent to server
At this point I need something that checks each second if userX(that could be user1 or user2) has new messages to display.
If I put something like:
while True:
time.sleep(1)
checkAndDisplayNewMessages()
the GUI doesn't appear! Because at the end of the code I got a mainloop()
To resume, I want my code to give the possibility to the user to send and receive messages asynchronously! With a part of code for sending messages if the user type in any message and the other part to constantly check for new messages while the program runs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你没有提到你正在使用哪个 GUI 工具包;来自
mainloop()
我猜是 Tk。此问题的答案解释了如何设置重复事件。 不需要多线程。
You did not mention which GUI toolkit you are using; from
mainloop()
I guess it's Tk.The answer to this question explains how to set up a recurring event. Multithreading is not required.
您需要将获取新消息的方式与应用程序的主线程分离。这可以通过 Python 中的 threads 轻松完成,它看起来像这样
:实现将与该过程并行运行以寻找更多消息,并且还将启动 UI。 UI 与寻找消息的过程同步非常重要,否则您最终会遇到有趣的异常。这是通过 fetch_messages 函数中的第一个循环实现的。
You need to detach the way you fetch for new messages from the main thread of your applications. That can be easily done with threads in Python, it'd look something like this:
This implementation will run in parallel the process to seek for more messages and also will launch the UI. It is important that the UI is sync with the process to seek for messages otherwise you'd end up with funny exceptions. This is achieved by the first loop in the
fetch_messages
function.