Python Tkinter button not appearing?

12,173

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.

Share:
12,173
Jaydreamer
Author by

Jaydreamer

Updated on June 08, 2022

Comments

  • Jaydreamer
    Jaydreamer almost 2 years

    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!

  • mhawke
    mhawke almost 10 years
    Button needs a container into which to be packed, which is not the case in your first example.
  • sundar nataraj
    sundar nataraj almost 10 years
    @mhawke please check now
  • mhawke
    mhawke almost 10 years
    That's better. What happens when you run it?
  • sundar nataraj
    sundar nataraj almost 10 years
    @mhawke present system doesnt have tkinter installed
  • mfit
    mfit over 3 years
    A short explanation might also help (even if it is somewhat obvious here).