How can I set the text widget contents to the value of a variable in Python/Tkinter?
Asked Answered
G

2

14

I am writing a program to assist with a trivial part of my job that can be automated. My purpose here is to:

  1. Copy and paste a chunk of plain text into a Tkinter text widget

  2. Use that pasted chunk of text as the value of a variable so that the variable can have certain characters pulled and returned down the line.

I have a functioning little bit of code. For example, here is my text widget and the lines of code I use to get and print its contents:

textBox = Text(root)

textBox.focus_set()

def get_input():
    print textBox.get(1.0, 'end-1c')

Then I use a button that uses the command get_input. It works when it comes to printing the contents of the widget.

Now that I know how to properly call on the contents and 'get' them, I would like to learn how I can assign those contents (a string) to the value of a variable.

Goodfellowship answered 20/6, 2015 at 17:46 Comment(2)
Are you asking how to assign the results of a function call to a variable? Like the_text = textBox.get(...)?Ardine
Bryan Oakley, yes thats what I want. I need my code to eventually interact with the text i put into the entry field.Goodfellowship
L
22

I think what you want is this. It will delete all the text and then insert a variable.

def set_input(value):
    text.delete(1.0, "END")
    text.insert("END", value)

It is Python 2.x only. Python 3 requires that "END" be END from the Tk namespace.

Leicestershire answered 20/6, 2015 at 19:24 Comment(4)
Insert a variable? What does it mean?Sternutatory
In the OP's question, he said he wanted to (I think) set the value of the text. This deletes all the text, then inserts the variable, basically overwriting it.Leicestershire
Still does not make any sense for me.Sternutatory
Right, so in Tkinter, you can't directly set the value of a text widget, so you have to delete all the text, then insert the text you want to set it to.Leicestershire
A
4
def set_value():
    text.insert("end-1c", value)
Artie answered 25/9, 2019 at 12:45 Comment(1)
OK, so it's a useful answer. However, it's the normal 'style' on Stack Overflow to offer an explanation with your answer - even if this is very brief.Cadenza

© 2022 - 2024 — McMap. All rights reserved.