I'm new to tkinter and I have this code in python:
#import the tkinter module
from tkinter import *
import tkinter
calc_window = tkinter.Tk()
calc_window.title('Calculator Program')
button_1 = tkinter.Button(text = '1', width = '30', height = '20')
button_1 = '1'
calc_window.mainloop()
But when I run it, the button doesn't appear. Does anyone know why? Thank you!
Getting a widget to appear requires two steps: you must create the widget, and you must add it to a layout. That means you need to use one of the geometry managers pack, place or grid to position it somewhere in its container.
For example, here is one way to get your code to work:
button_1 = tkinter.Button(text = '1', width = '30', height = '20')
button_1.pack(side="top")
The choice of grid or pack is up to you. If you're laying things out in rows and columns, grid makes sense because you can specify rows and columns when you call grid. If you are aligning things left-to-right or top-to-bottom, pack is a little simpler and designed for such a purpose.
Note: place is rarely used because it is designed for precise control, which means you must manually calculate x and y coordinates, and widget widths and heights. It is tedious, and usually results in widgets that don't respond well to changes in the main window (such as when a user resizes). You also end up with code that is somewhat inflexible.
An important thing to know is that you can use both pack and grid together in the same program, but you cannot use both on different widgets that have the same parent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With