First of all, you need to fix that line:
Box = Entry().pack()
The problem here is that the method pack()
does not return anything, so its variable Box
will be empty (with None
). To store the object Entry
in Box
you need to split it into two lines:
Box = Entry()
Box.pack()
Now, your problem is passing the data from one function to another. As the function called by Button
cannot have parameters, you need to use some alternative method to pass the object Entry
for the same.
One of the simplest ways is to use global variables: For this use global
in both roles:
def main_screen():
global Box
# ... restante da funcao normal ...
def Connect():
global Box
ip_digitado = Box.get() # acessa o Entry criado na outra funcao
print(ip_digitado)
Another way is to use the scope of a function to hold the variable (called closure). The module functools
has the function partial
that’s what this:
By creating the Button
:
Button(..., command=functools.partial(Connect, Box)).pack()
When calling using this function partial
it is possible to pass a parameter to Connect
which is of local scope within main_screen
; That way you don’t need to use global
, just receive the parameter:
def Connect(box):
ip_digitado = box.get()
print(ip_digitado)
The third, and most recommended, form is to use classes, and then store the objects you will need as instance attributes:
class App:
def __init__(self, root):
self.screen = root
def main_screen(self):
self.screen.geometry("800x600")
self.screen.title("Helpdesk")
Label(self.screen, text="Helpdesk 1.0", bg="grey", width="300",
height="2", font=("calibri", 13,)).pack()
Label(self.screen, text="IP Adrress", bg="white", width="250",
height="2", font=("calibri",12,)).pack()
self.box = Entry(self.screen)
self.box.pack()
Button(self.screen, text="Connect", height="2", width="30",
command=self.connect).pack()
self.screen.mainloop()
def connect(self):
ip_digitado = self.box.get()
print(ip_digitado)
screen = Tk()
App(screen).main_screen()
As you can see the attribute self.box
is accessible in any class method, making it independent.