0

I am working on a simple application that will get some values from the Server (continuously) and using those values will draw them on a canvas made using Tkinter. The problem is that the mainloop function of the Tkinter module makes it impossible to get the values as the loop is never entered and since I have to get the values continuously the loop is an infinite loop and in that case the GUI is not visible since the loop keeps on running. So what do I do? How do I proceed?

I read this question and also this question. The answers suggest Twisted. Any other way to do so?

The code for the server is:

import socket
import pickle
import random
import time

data=[]
s=socket.socket()
host=socket.gethostname()
port=12345
s.bind((host,port))

s.listen(5)
c,addr=s.accept()
while True:
    data=str(random.randint(100,500))
    c.send(data)
    time.sleep(1)

c.close

The code for the client is:

import Tkinter as tk
import socket
import pickle

root = tk.Tk()
canvas = tk.Canvas(root, width=800, height=800, borderwidth=0, highlightthickness=0, bg="white")
canvas.grid()

canvas.create_line(170,400,630,400)
canvas.create_line(400,170,400,630)

#draw things on the canvas

s=socket.socket()
c=[]
host=socket.gethostname()
port=12345
s.connect((host,port))
while True:
    a=s.recv(1024)
    c.append(int(a))
    print c
s.close

root.mainloop()
Community
  • 1
  • 1
praxmon
  • 5,009
  • 22
  • 74
  • 121
  • 2
    You implement some form of multithreading. Either by conventional `threads` or something more 'modern' like `Twisted` or `gevent`. Please show us your code so far. – msvalkon Feb 14 '14 at 12:58
  • 2
    Have you tried to _poll_ the network from an alarm installed in the GUI code? I. e. let the GUI have an alarm now and then (e. g. each second) which is then executed in the main thread and which has a look at whether there is something coming from the network. This is not the most elegant solution (polling never is) but maybe one which you can implement yourself without problems. – Alfe Feb 14 '14 at 13:10
  • Have a look at this: http://stackoverflow.com/questions/21532523/tkinter-loop-and-serial-write – User Feb 14 '14 at 14:01
  • @Alfe would polling be computationally expensive? I mean from your comment is seems so. Anyway, I'll look it up. – praxmon Feb 17 '14 at 04:27
  • Polling is either expensive (if you poll often) or has latencies (if you poll just from time to time). But in many cases it is a good solution. In your case, polling once a second for data from the server would probably solve the issue without raising others. Unless you hate having your computer more busy than it needs to be. – Alfe Feb 17 '14 at 10:09

0 Answers0