0

I'm trying to pass a value which is entered by the user at runtime in a textbox using text.get()

The following code is what I'm using:

from tkinter import *
from tkinter import ttk

root = Tk()
#LABEL
label = ttk.Label(root,text = 'FUNCTION CALL')
label.pack()
label.config(justify = CENTER)
label.config(foreground = 'blue')

Label(root, text="ENTER TEXT: ").pack()

#TEXTBOX
text = Text(root,width = 40, height = 1)
text.pack()
text_value = text.get('1.0', '1.end')

#BUTTON
button = ttk.Button(root, text = 'PASS')
button.pack() 

#FUNCTION DEF
def call(text_value):
    print(text_value)

button.config(command = call(text_value))   

root.mainloop()

However the program is fully executed before the text in the textbox is passed into the function and printed

How to get the user input from the textbox and pass it into the function and then execute the function upon clicking the button

2 Answers2

1

1: Why is Button parameter “command” executed when declared

2: Another problem - you trying to get user input before mainloop and only once, so there're no user input at all. To overcome this - get user input on button click event (when you really need it):

...
#TEXTBOX
text = Text(root,width = 40, height = 1)
text.pack()

#BUTTON
button = ttk.Button(root, text = 'PASS')
button.pack()

#FUNCTION DEF
def call():
    text_value = text.get('1.0', '1.end')
    print(text_value)

button.config(command = call)

root.mainloop()
Community
  • 1
  • 1
CommonSense
  • 4,232
  • 2
  • 14
  • 38
0

You have 2 problems:

  • First, the text_value content of your Text box is only read once, so it won't be updated after the user types in something.
  • Second, when binding a command to a button, you have to pass the function handle, instead of calling the function (see here).

This should give you the behavior you want:

def call():
    print(text.get('1.0', '1.end'))

button.config(command=call)
Community
  • 1
  • 1
Josselin
  • 2,593
  • 2
  • 22
  • 35