How to pass the input of a textbox to a variable in python tkinter?

Question:

I am trying to make a variable that stores the input inside a textbox on the press of the button. As an example:

when button1 pressed:
a = textbox1.input

My current code so far is:

import tkinter as tk
window = tk.Tk()
window.title("A simple window")
window.geometry("150x150")
def save_textbox_input():
 # Code goes here
button = tk.Button(text="Click me to save textbox input",command=save_textbox_input)
textbox = tk.Text(width="30",height="2")
button.pack()
textbox.pack()
tk.mainloop()

I didn’t manage to think of any code I could use to do this, other than use the console, as an example:

a = input('Write code here instead of inside textbox: ')

It did in fact ask the player to input something in the console and store it inside a variable, but I want to store the input inside a textbox: textbox = tk.Textbox(height="2",width="25")

Asked By: bogdanel2011 Sandu

||

Answers:

use the get() method of the textbox widget to get its input and store it in a variable.

An example:

def save_textbox_input():
    a = textbox.get("1.0", "end-1c")  newline character
    print(a) 
Answered By: Abdulmajeed

In order to retrieve a input from a textbox and store it in a variable, you can use the get() method of the textbox object inside the save_textbox_input() function.

Example:

import tkinter as tk

window = tk.Tk()
window.title("A simple window")
window.geometry("150x150")

def save_textbox_input():
    input_text = textbox.get("1.0", "end-1c")
    print("Input text:", input_text)

button = tk.Button(text="Click me to save textbox input", command=save_textbox_input)
textbox = tk.Text(width="30", height="2")
button.pack()
textbox.pack()

tk.mainloop()

Updated with Complete code.

Answered By: Christophermp
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.