How to add data from tk.Entry to f'string in Python 3?

Question:

I need to make a text generator in which user input is added to f’string. What I get in result is that data typed in entry can be printed in PyCharm console, but doesn’t show up in generated strings in tk.Text. Thank you in advance!

Here is the code of my randomizer:

Simple GUI interface:

import tkinter as tk
import random

win = tk.Tk()
win.title('TEXT MACHINE')
win.geometry('1020x600+400+250')
win.resizable(False, False)

Here I want a variable anchor to assign a data from entry

anchor = tk.StringVar() 
entry_1 = tk.Entry(win, textvariable=anchor)
entry_1.grid(row=1, column=1, padx=20, sticky='wn')

def add_text():
    text_generated = (random.choice(first_text) + random.choice(second_text)
                      )
    text.delete('1.0', tk.END)
    text.insert('insert', text_generated)

btn_1 = tk.Button(win, text='GENERATE TEXT', command=add_text, height=5, width=50)
btn_1.grid(row=1, column=0, pady=10, padx=20, sticky='w')

lbl_1 = tk.Label(win, text='Place Your Anchor Here')
lbl_1.grid(row=0, column=1, padx=20, sticky='ws')

text = tk.Text(win, width=120)
text.grid(row=2, column=0, columnspan=2, padx=(20, 120))

win.grid_rowconfigure(0, pad=50)
win.grid_columnconfigure(0, pad=50)

first_text = ['First text 1', 
              'First text 2', 
              'First text 3'
              ]
second_text = [f'Second text 1{anchor.get()}',
               f'Second text 2{anchor.get()}',
               f'Second text 3{anchor.get()}'
              ]

When I generate text I get empty space instead of anchor, but when I do print(anchor.get()) it shows up in my console correctly.

Asked By: Alex Nilson

||

Answers:

The issue is that you’re essentially calling anchor.get() immediately after declaring it with anchor = tk.StringVar(). It seems like what you really want is entry_1.get(), in which case you can do away with the anchor variable entirely.

entry_1 = tk.Entry(win)

You’ll also probably want to move the definition of second_text (and maybe also first_text, for consistency) to inside the add_text() function. That way the call to entry_1.get() is performed on each button press instead of immediately (and only once)

def add_text():
    first_text = ['First text 1', 'First text 2', 'First text 3']
    second_text = [
        f'Second text 1{entry_1.get()}',
        f'Second text 2{entry_1.get()}',
        f'Second text 3{entry_1.get()}'
    ]
    text_generated = (random.choice(first_text) + random.choice(second_text))
    text.delete('1.0', tk.END)
    text.insert('insert', text_generated)
Answered By: JRiggles
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.