简体   繁体   中英

Real-time Tkinter/ttk Entry widget update: thread+queue or .after(1)?

I have a Tkinter/ttk app that analyzes packets arriving every 10-25 ms. My present implementation uses a thread that updates 30 StringVars after every socket read, then calls update_idletasks() to update the corresponding Entry widgets. My app crashes no more than 30 minutes after starting.

Searches revealed that Tk isn't really thread-safe, and I have two main choices:

  1. Use a thread + queues.

  2. Use a function + .after(1, function).

The UI does little more than start/stop the updates, and provide the Entry widgets for display.

The primary wait in the system is the socket read, which has a timeout of 2x the expected packet rate (so it can't block forever).

In this case, would you prefer approach #1 or #2?

I'm leaning toward #2 for its simplicity, but I'm not sure if there are any Tk gotchas waiting along that path. I'll probably try both while I await the community wisdom.

My personal rule of thumb is to avoid threads unless they are strictly required. Threads add complexity. Plus, there's a large percentage of programmers who aren't particularly thread-savvy, so threads add an element of risk if this program will be used or maintained by others.

That being said, in this particular case I think I'd go with thread + queues. Since you know how often the display should update, I'd set up a poll of the queue for every 10ms or so to update the widgets.

I just implemented #2 (function + .after(1, function)) by changing literally 8 lines of code in my original implementation, and it runs perfectly. So #2 wins based on simplicity and effectiveness. It runs using 3-4% of 1 core (i5-2500, 3.3 GHz)

But if my UI becomes more complex, such as by adding stripchart recording via matplotlib animation, then queues and a separate acquisition thread may become necessary. But not today!

EDIT: But don't use .after(0, ...): My UI locked up when I tried it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM