2

I managed to create 2 classes that run independently in Python. I want to pass the data variable received from the class DataCom() to tkinter cf_label on the second class.

Is this a correct way to start? I understand that I have to make some variable public in some way but I cannot figure it out. Could someone please help?

from Tkinter import *
import socket
import sys
import time
import datetime
from threading import Thread

def get_constants(prefix):
    """Create a dictionary mapping socket module constants to their names."""
    return dict( (getattr(socket, n), n)
                 for n in dir(socket)
                 if n.startswith(prefix)
                 )


class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.friend_check = IntVar()
        self.parent = parent
        self.initUI()

    def initUI(self):      
        self.parent.title("Home.local")


        self.cl_label=Label(text="data from socket")
        self.cl_label.grid(row=0,column=0,columnspan=2)



class DataCom(Thread):
    def __init__(self, val):
        Thread.__init__(self)
        self.val = val
    def run(self):
        families = get_constants('AF_')
        types = get_constants('SOCK_')
        protocols = get_constants('IPPROTO_')

        # Create a TCP/IP socket
        sock = socket.create_connection(('localhost', 10000))

        while True:
            try:

                message = 'INFO'

                print >>sys.stderr, 'sending "%s" Length: %s' % (message,len(message))

                sock.sendall(message)

                amount_received = 0
                amount_expected = len(message)

                while amount_received < amount_expected:
                    data = sock.recv(1024)
                    amount_received += len(data)
                    if len(data) != 0:
                        print >>sys.stderr, 'Server received %s %s:Length %s' % (data, len(data))
                    else:
                        sock.close()
                        print >>sys.stderr, 'No more data, closing socket'
                        break
                if not data:
                        break

            finally:

                time.sleep(1)

def main():

    myThread1 = DataCom(4)
    myThread1.setName('Thread 1') 
    myThread1.start()

    root = Tk()

    root.geometry("600x450+900+300")
    root.resizable(0,0)
    app = Example(root)
    root.mainloop()  


if __name__ == '__main__':
    main()  
1
  • I still not understand how can I pass data from DataCom.data to tkinter label Example Frame. Commented Aug 2, 2015 at 2:03

2 Answers 2

2

If you're using threads try using a Queue to share data between threads.

The other option is to declare your variable in class DataCom() as global but be warned, this can cause a lot of confusion and bugs.

A couple of great StackOverflow questions and answers on the subject:

Sign up to request clarification or add additional context in comments.

1 Comment

Queues are useful if you want to synchronize the activity of multiple threads. They are unnecessary if all you want to do is share data, since all Python variables occupy the same address space (unless you are using multiple processes, which is not the case here). There is no need for a global variable that I can see.
2

You don't need a public variable, you just need to pass myThread1 as a second parameter to the Example constructor. Then modify Example.__init__ to assign the new argument to a member variable, say theThread. Now all the code in Example can access DataCom.data as self.theThread.data.

1 Comment

I thought it was easy but it looks like I will sit tonight to read more about until I will understand this new notions. Appreciate your help. Python is nice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.