busymind
busymind

Reputation: 69

Pass variable from one class to another Python

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()  

Upvotes: 2

Views: 1388

Answers (2)

Paul Cornelius
Paul Cornelius

Reputation: 11009

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.

Upvotes: 2

Ewan
Ewan

Reputation: 15068

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:

Upvotes: 2

Related Questions