Python Tkinter display the name with Hi in front of it

Viewed 691
  • Hello I'm a few weeks into python and I'm now starting learning tkinter. The button should have the text Say hello and when the user clicks the button, the bottom label should display the name with Hi in front of it. However I cannot get the label to display "Hi {name}". Could someone help me?
from tkinter import *
from tkinter.ttk import *

def process_name():
    """Do something with the name (in this case just print it)"""

    global name_entry
    print("Hi {}".format(name.get()))
    

def main():
    """Set up the GUI and run it"""

    global name_entry
    window = Tk()
    
    name_label = Label(window, text='Enter name a name below:')
    name_label.grid(row=0, column=0)
    name_entry = Entry(window)
    name_entry.grid(row=1, column=3)
    button = Button(window, text='Say hello', command=process_name, padding=10)
    button.grid(row=1, column=0, columnspan=2)
 
    window.mainloop()

        
main()
  • I've tried using set() but it doesn't display. Thank you.
1 Answers

This should work for your needs. Make sure to read the code comments to understand what I did properly.

Few points though,

  • Not recommended to use wildcard import like from tkinter import * . The reason is simple. both tkinter and tkinter.ttk have common classes and functions like Button, Label and more. It becomes ambiguous for interpreter to decide which ones to use.
  • use .config() or .configure() to update labels, buttons, entries or text widgets in tkinter. Like I did in code below.

Your code modified

from tkinter import *
from tkinter.ttk import *

def process_name():
    """Do something with the name (in this case just print it)"""

    global name_entry # this will print hi {name} to terminal.
    print("Hi {}".format(name_entry.get()))

    global nameLabel # to change'the label with hi{name} text below the button.
    nameLabel.configure(text=f'Hi {name_entry.get()}')

    
    

def main():
    """Set up the GUI and run it"""

    global name_entry, nameLabel
    window = Tk()
    
    name_label = Label(window, text='Enter name a name below:')
    name_label.grid(row=0, column=0)
    name_entry = Entry(window)
    name_entry.grid(row=1, column=3)
    button = Button(window, text='Say hello', command=process_name, padding=10)
    button.grid(row=1, column=0, columnspan=2)

    # I defined a label BELOW the button to show how to change
    nameLabel = Label(window, text=' ') # an empty text Label
    nameLabel.grid(row=2)
 
    window.mainloop()

        
main()
Related