Python Set Label Text on Button Click tkinter GUI Program

By | March 22, 2020

Topic: Python Set Label Text on Button Click tkinter GUI Program

 

# Write a Python GUI program
# using tkinter module
# to set text "Easy Code Book" in Label
# on button click. 

import tkinter as tk



def main():
    window= tk.Tk()
    window.title("Show Label and Button Widgets")
    window.geometry("400x200")
    
    # create a label with some text 
    label1 = tk.Label(window, text="")
    
    # place this label in window at position x,y 
    label1.place(x=130,y=50)
    txt = "Easy Code Book"

    def btn1_click():
        label1.configure(text = txt)

    # create a button with text Button 1
    btn1 = tk.Button(window, text="Click Me", command=btn1_click)
    # place this button in window at position x,y 
    btn1.place(x=150,y=100)
    window.mainloop()
    

main()
Python 3 Set Label Text on Button Click tkinter GUI Program

Python 3 Set Label Text on Button Click tkinter GUI Program

Explanation of Code in the Image

  1. Comments
  2. Comments
  3. Comments
  4. Comments
  5. Blank
  6. Imports tkinter module, use tk as an alias. Because tk is short and easy to use in code.
  7. Header of main() function.
  8. Indented body of main() function . Create main window or Root window of the application.
  9. Set title of the main window.
  10. Set size of the main window.
  11. Comments
  12. Create a label with empty text.
  13. Comments
  14. Place label in the main window at x,y location.
  15. Define and set a txt variable to “Easy Code Book” string literal.
  16. Define btn1_click() function to handle the button click event.
  17. Set the text of label to txt variable.
  18. Comments
  19. Create a button and bind it to btn1_click event handler by setting command option.
  20. Comments
  21. Place button in the root window at x,y position.
  22. When this line of code will execute, it will start the mainloop that is event loop. So that the output root window is shown to the user. It will wait for any actions called events performed by the user and the code attached, if any, will respond to those events. For example, if we click on close button, the window will be closed.
  23. Call to main() function. Now the execution of the program will start and the root window will be displayed on the screen.

Loading

One thought on “Python Set Label Text on Button Click tkinter GUI Program

  1. Pingback: Multiplication Table Python GUI Program | EasyCodeBook.com

Leave a Reply

Your email address will not be published. Required fields are marked *