How to Add Button in Tkinter in Python: Simple Guide
To add a button in
tkinter in Python, first create a Button widget with the parent window and text label, then use the pack() method to display it. For example, button = Button(root, text='Click me') creates the button, and button.pack() shows it on the window.Syntax
The basic syntax to add a button in tkinter is:
Button(parent, text='label', command=callback): Creates a button widget inside theparentwindow.text: The label shown on the button.command: (Optional) A function to run when the button is clicked.pack(),grid(), orplace(): Methods to display the button on the window.
python
button = Button(root, text='Click me', command=some_function)
button.pack()Example
This example creates a window with a button labeled 'Click me'. When clicked, it prints a message in the console.
python
import tkinter as tk def on_click(): print('Button was clicked!') root = tk.Tk() root.title('Button Example') button = tk.Button(root, text='Click me', command=on_click) button.pack(padx=20, pady=20) root.mainloop()
Output
A window appears with a button labeled 'Click me'. Clicking the button prints 'Button was clicked!' in the console.
Common Pitfalls
Common mistakes when adding buttons in tkinter include:
- Forgetting to call
pack(),grid(), orplace(), so the button does not appear. - Not defining the
commandfunction or calling it with parentheses, which runs it immediately instead of on click. - Using
command=on_click()instead ofcommand=on_click, causing the function to run once at start.
python
import tkinter as tk def on_click(): print('Clicked') root = tk.Tk() # Wrong: function called immediately button_wrong = tk.Button(root, text='Wrong', command=on_click()) button_wrong.pack() # Right: function passed without parentheses button_right = tk.Button(root, text='Right', command=on_click) button_right.pack() root.mainloop()
Output
The 'Wrong' button triggers the print immediately when the program starts, not on click. The 'Right' button prints only when clicked.
Quick Reference
Summary tips for adding buttons in tkinter:
- Use
Button(parent, text='label', command=func)to create buttons. - Always call
pack(),grid(), orplace()to show the button. - Pass the function name to
commandwithout parentheses. - Use
padxandpadyinpack()for spacing.
Key Takeaways
Create a button with Button(parent, text='label', command=func) and display it with pack(), grid(), or place().
Pass the function name to command without parentheses to run it on click.
Always call a geometry manager method like pack() to make the button visible.
Use padding options in pack() to add space around the button for better layout.