我在将GUI集成到我的python程序中时遇到问题

时间:2019-07-23 19:56:13

标签: python sockets user-interface tkinter

我敢肯定这是一个简单的解决方法,但我只是在基础知识上略作介绍。我需要合并一个GUI,该GUI会简单弹出,并指出已在客户端和服务器之间建立了连接。

当带有所有变量的代码位于我的代码顶部时,我可以使GUI弹出,但是它不会在我的代码下运行,这是我需要显示的连接所在的地方。

# it will run but (address) is not defined yet
import socket
from tkinter import *

root = Tk()
theLabel = Label(root,text="Connection from {address} has been established.")
theLabel.pack()
root.mainloop()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)

while True:
  clientsocket, address = s.accept()
  print(f"Connection from {address} has been established.")
  clientsocket.send(bytes("HELL YEAH FAM!!! WE DID IT!!","utf-8"))
  clientsocket.close()

它没有错误消息,只是不会运行GUI。

2 个答案:

答案 0 :(得分:2)

您必须配置所有内容,然后才能调用用于连接的函数,然后最后调用root.mainloop()。这是您需要做的一些工作:

public final class MyViewModelFactory implements Factory {
    private final Repository repository;
    private String uid;

   @Inject
   public MyViewModelFactory(Repository repository) {
      this.repository = repository;
   }

   @NotNull
   public ViewModel create(@NotNull Class modelClass) {
      if (modelClass.isAssignableFrom(MyViewModel.class)) {
         return new MyViewModel(repository, uid);
      } else {
         throw (Throwable)(new IllegalArgumentException("Unknown ViewModel class [" + modelClass + ']'));
      }
   }

   public void setUid(@NonNull final String uid) {
       this.uid = uid;
   }
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
    String uid = "123"; //How to pass this String??
    factory.setUid(uid);
    MyViewModel viewModel = ViewModelProviders.of(this, factory).get(MyViewModel.class);
    LiveData<User> liveData = viewModel.getUserLiveData();
}

答案 1 :(得分:0)

您应该使用线程等待连接:

import socket
import threading
from tkinter import *

def wait_connection():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((socket.gethostname(), 1234))
    s.listen(5)

    while True:
        clientsocket, address = s.accept()
        msg.set(f"Connection from {address} has been established.")
        clientsocket.send(bytes("HELL YEAH FAM!!! WE DID IT!!","utf-8"))
        clientsocket.close()

root = Tk()
msg = StringVar(value='Waiting for connection ...')
theLabel = Label(root,textvariable=msg)
theLabel.pack()

# start a thread for waiting client connection
threading.Thread(target=wait_connection, daemon=True).start()

root.mainloop()