我有一个简单的客户端程序,它连接到服务器并发送一些信息。它最初使用输入函数来发送数据,但我希望它在GUI中,因此您可以按一个按钮来发送数据。但是我一直收到名称错误,当我尝试使用按钮调用它时,它没有定义sendinfo
。
# client.py
import socket import sys from tkinter import Tk, Label, Button
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect(("127.0.0.1", 12345))
#clients_input = input("What you want to proceed my dear client?\n")
#soc.send(clients_input.encode("utf8")) # we must encode the string to bytes
#result_bytes = soc.recv(4096) # the number means how the response can be in bytes
#result_string = result_bytes.decode("utf8") # the return will be in bytes, so decode
#print("Result from server is {}".format(result_string))
class GUI:
# some sort of initialise
def __init__(self, master):
self.master = master
master.title("Our Server GUI")
self.label = Label(master, text="This is our Server GUI!")
self.label.pack()
self.greet_button = Button(master, text="Send", command=sendinfo(self))
self.greet_button.pack()
self.close_button = Button(master, text="Quit", command=master.quit)
self.close_button.pack() class DataSend:
def sendinfo(self):
test = 666
soc.send(test.encode("utf8"))
result_byte = soc.recv(4096)
result_strings = result_byte.decode("utf8")
print("Result from server is {}".format(result_strings))
## Run program to
## 1 - Open a GUI root = Tk() my_gui = GUI(root)
root.mainloop() #Runs the GUI on a loop so it always shows?
错误:
C:\Users\stuar\PycharmProjects\test\venv\Scripts\python.exe
F:/College/CyberLvl5/Feb/Programming/TestClient.py Traceback (most
recent call last): File
"F:/College/CyberLvl5/Feb/Programming/TestClient.py", line 43, in
<module>
my_gui = GUI(root) File "F:/College/CyberLvl5/Feb/Programming/TestClient.py", line 27, in
__init__
self.greet_button = Button(master, text="Send", command=sendinfo(self)) NameError: name 'sendinfo' is not defined
Process finished with exit code 1
答案 0 :(得分:2)
使用
行self.greet_button = Button(master, text="Send", command=sendinfo(self))
你告诉Python“使用参数sendinfo
调用全局函数self
并将该函数调用的结果绑定到command
”。但是该名称的全局函数不存在,并且调用它并将结果绑定到command
也没有意义。相反,您希望将方法 sendinfo
self
本身绑定到命令,就像您所做的那样关闭按钮。
self.greet_button = Button(master, text="Send", command=self.sendinfo)