[Tutor] Tkinter widget (label) updated by TCP/IP message
Alan Gauld
alan.gauld at yahoo.co.uk
Sun May 27 13:03:29 EDT 2018
On 27/05/18 16:18, Alejandro Chirife via Tutor wrote:
>
> Hi all, I am having a hard time to create what at first looked like a simple program with Python 3 and Tkinter:
> The UI consist of a window with a label and a button.
> The label shows "waiting for a message" and the button shows "reset display".
> The handler for the button click just resets the label text to "waiting for a message".
So far so good, it is all standard Tkinter programming but....
> The program would draw the window with the two widgets with root.mainloop()> while it is capable of listening on a TCP port for an arriving message
This is not so good. You can't do anything in your code after you call
mainloop(). Thats just the nature of event driven programming. Once
mainloop() is called all control rests with the GUI and you can only
respond to events. Sooo....
> like "hello world", and when it arrives it would show the text in the label.
You need to put your network listener in a separate thread started
before you call mainloop(). Then when a message is received you need to
generate an event in your Tkinter GUI (or you could just call an event
handler directly but that's considered bad practice (for some good
reasons!).
> The received message should show in the label until any of the following occurs:
>
> - Has been shown for 10 seconds
Set a timer in the GUI that expires after 10 seconds
- Another packet arrived with new message (will show the new message in
the label)
Generate (or call) the same event as before but don't
forget to cancel the current timer.
- User clicks on the "reset display" button
In the button event handler
- Cancel the timer.
- Display whatever the reset message says
So in pseudo code you need:
import tkinter as tk
def button_click()
cancel timer
display default message
def display_message(msg):
display msg on label
cancel current timer
create new 10s timer
def timeout():
display ???
def get_network_message()
your network receiving code here
....
if is_valid_message(msg):
display_message(msg)
def main():
create GUI
bind events
create thread to run get_network_message
mainloop()
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list