I am using a TKinter GUI on a Raspberry Pi. The user enters a number in an entry field of that GUI and presses return. After that, the entry is validated and sent to a PC (TCPIP). PC will answer and GUI display will be updated (Get user entry -> validate -> send to PC -> PC accept or reject command -> message appears on GUI label)
I have made seperate classes for the GUI and entry validation/TCP-IP communication. I create the GUI instance "app" and the instance Communication, It is necessary to access some variables from GUI, therefore I must commit the instance "app" as a parameter to the communication class -> Communication(app)
The problem is that I cannot start the GUI with app.root.mainloop first because everything after the mainloop commad will be ignored till I destroy the GUI window. No communication/validation possible.
Try 1:
app = Gui()
app.root.mainloop()
print("Cannot reach that code because of GUI main loop")
Communicator = Communication(app)
print("[STARTING] server is starting...")
print("[WAITING] looking for connection...")
listenthread = threading.Thread(target=Communicator.startcommunication())
listenthread.start()
if __name__ == '__main__':
main()
But on the other side: If I change the order and create the instance "Communicator" before the mainloop.command, it is also not working and I get an error message (Gui object has no attribute....) because Communicator = Communication(app) doesn´t know the parameter "app" at this time (I think that´s the reason).
Try 2:
def main():
app = Gui()
Communicator = Communication(app)
print("[STARTING] server is starting...")
print("[WAITING] looking for connection...")
listenthread = threading.Thread(target=Communicator.startcommunication())
listenthread.start()
app.root.mainloop()
# if mainloop command is at this point Communicatior instance cannot be created because class doesn´t now the parameter "app" yet.
if __name__ == '__main__':
main()
I have no idea how to solve that problem except to move all the code in the GUI class. Is there another chance to get it to work with different classes?
Thanks in advance!
First of all change
listenthread = threading.Thread(target=Communicator.startcommunication())
into
listenthread = threading.Thread(target=Communicator.startcommunication)
Otherwise you are calling Communicator.startcommunication()
and then setting target
to whatever startcommunication
returns (which is probably None
).
Second of all make sure that the startcommunication
function doesn't use any of the tkinter variables. tkinter
doesn't allow itself to be called from multiple threads (no way around it unless you use queues).
Note: I don't know what your startcommunication
function does so if you edit your answer with the code from the startcommunication
function, I will be able to improve this answer