-2

I have a simple client program that connects to a server and sends some information across. It originally used the input function to send over data, but I'd like it to be in a GUI, so you can press a button to send the data across. But I keep getting a name error, it says sendinfo is not defined when I try to call it using a button.

# 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?

Error:

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
martineau
  • 119,623
  • 25
  • 170
  • 301
Chenko
  • 35
  • 6

1 Answers1

2

With the line

self.greet_button = Button(master, text="Send", command=sendinfo(self))

you tell Python "call the global function sendinfo with parameter self and bind the result of that function call to command". But a global function of that name does not exist, and invoking it and binding the result to command does not make sense, either. Instead, you want to bind the method sendinfo of self itself to the command, just like you did for the close button.

self.greet_button = Button(master, text="Send", command=self.sendinfo)
tobias_k
  • 81,265
  • 12
  • 120
  • 179