我正在使用一个TKinter图形用户界面上的覆盆子Pi。用户在该GUI的输入字段中输入一个数字,然后按回车键。然后,验证该条目并将其发送到PC (TCPIP)。PC将响应并更新图形用户界面显示(获取用户条目->验证->发送到PC -> PC接受或拒绝命令->消息出现在GUI标签上)
我已经为GUI和条目验证/TCP通信分别创建了类。我创建了GUI实例"app“和实例通信,需要从GUI访问一些变量,因此必须将实例"app”作为通信类->通信(App)的参数来提交。
问题是,我不能首先使用app.root.mainloop启动GUI,因为在销毁GUI窗口之前,主循环逗号之后的所有内容都将被忽略。不可能进行通信/验证。
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()但另一方面:如果我更改顺序并在mainloop.command之前创建实例"Communicator“,它也不起作用,并得到错误消息(Gui对象没有属性.)因为Communicator = Communication(app)此时不知道参数"app“(我认为这就是原因)。
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()除了移动GUI类中的所有代码之外,我不知道如何解决这个问题。还有其他的机会让它与不同的类一起工作吗?
提前感谢!
发布于 2021-03-31 13:31:25
首先是改变
listenthread = threading.Thread(target=Communicator.startcommunication())转到
listenthread = threading.Thread(target=Communicator.startcommunication)否则,您将调用Communicator.startcommunication(),然后将target设置为任何startcommunication返回(可能是None)。
其次,确保startcommunication函数不使用任何tkinter变量。tkinter不允许从多个线程调用自己(除非使用队列,否则无法绕过它)。
注意:我不知道您的startcommunication函数是干什么的,所以如果您用startcommunication函数的代码编辑您的答案,我将能够改进这个答案。
发布于 2021-04-01 09:56:32
谢谢。现在起作用了。第一个问题是listenthread = threading.Thread(target=Communicator.startcommunication())。第五,括号发生了一些奇怪的错误,线程没有正确启动。第二个问题是,我意外地删除了Gui类中的变量声明。现在看起来是这样的,而且正在起作用。非常感谢!
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 __name__ == '__main__':
main()https://stackoverflow.com/questions/66888723
复制相似问题