w3resource

Python tkinter widgets Exercise: Add a button in your application using tkinter module


Write a Python GUI program to add a button in your application using tkinter module.

Sample Solution:

Python Code:

import tkinter as tk 
parent = tk.Tk() 
parent.title('Title - button') 
my_button = tk.Button(parent, text='Quit', height=1, width=35, command=parent.destroy) 
my_button.pack() 
parent.mainloop()

Explanation:

In the exercise above -

  • import tkinter as tk - Import the required libraries.
  • parent = tk.Tk() - Create the main Tkinter window.
  • parent.title('Title - button') - Create the title of the window.
  • my_button = tk.Button(parent, text='Quit', command=parent.destroy) - Create a "Quit" button that closes the window.
  • my_button.pack() - Display the button in the window.
  • parent.mainloop() - Start the Tkinter main loop.

Sample Output:

Tkinter: Add a button in your application using tkinter module

Flowchart:

Flowchart: Add a button in your application using tkinter module

Python Code Editor:


Previous: Python tkinter widgets Exercise Home
Next: Write a Python GUI program to add a canvas in your application using tkinter module.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.