Search code examples
pythontkinterlabeltkinter-entry

Generated Words Print to Terminal But Not GUI Entry - Tkinter


The purpose is to pull a word from the list randomly and display it on the screen in the GUI. The words are displayed in the terminal when I click the button "dammi" but I cannot get them to display in the GUI. I have tried both an Entry and Label with no success.

from tkinter import *
import random

# Window

root = Tk()
root.geometry("400x350")
root.title("Passato Remoto")
root.configure(bg="#000000")
root.resizable(False, False)

# Find Verb

verbi = ['Dare', 'Dire', 'Fare', 'Sapere', 'Prendere']

# Dammi Button

def give():
    print(random.choice(verbi))

# Create Buttons

dammi = Button(root, text='Dammi un verbo',
bg='#ffffff',
fg='#000000',
borderwidth=0,
highlightthickness=0,
font=('Helvetica', 16),
height=2,
width=10,
command=give)
dammi.grid(column=0, row=2, pady=50, padx=25)

con = Button(root, text='Coniugazione',
bg='#ffffff',
fg='#000000',
borderwidth=0,
highlightthickness=0,
font=('Helvetica', 16),
height=2,
width=10)
con.grid(column=2, row=2, pady=50, padx=25)

# Put Verb On Screen

verb = Entry(root, text=give(), font=('Helvetica', 40), width=10, bg="#ffffff", fg="#000000")
verb.grid(column=0, columnspan=3, row=1, pady=50, padx=80)

root.mainloop()



Solution

  • The easiest way is probably to use a StringVar. I've added this into the question code.

    from tkinter import *
    import random
    
    root = Tk()
    root.geometry("400x350")
    root.title("Passato Remoto")
    root.configure(bg="#000000")
    root.resizable(False, False)
        
    # Find Verb
        
    verbi = ['Dare', 'Dire', 'Fare', 'Sapere', 'Prendere']
       
    # Dammi Button
       
    sample = StringVar()           # Added
       
    def give():                    # Changed
        sample.set( random.choice(verbi) )
        print( sample.get() )
       
    # Create Buttons
       
    dammi = Button(root, text='Dammi un verbo',
       bg='#ffffff',
       fg='#000000',
       borderwidth=0,
       highlightthickness=0,
       font=('Helvetica', 16),
       height=2,
       width=10,
       command=give)
    dammi.grid(column=0, row=2, pady=50, padx=25)
       
    con = Button(root, text='Coniugazione',
       bg='#ffffff',
       fg='#000000',
       borderwidth=0,
       highlightthickness=0,
       font=('Helvetica', 16),
       height=2,
       width=10)
    con.grid(column=2, row=2, pady=50, padx=25)
           
    # Put Verb On Screen
    
    #                                          changed here
    verb = Label(root, font=('Helvetica', 40), textvariable = sample, width=10, bg="#ffffff", fg="#000000")
    verb.grid(column=0, columnspan=3, row=1, pady=50, padx=80)
    give()   
    root.mainloop()