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