0

I have created two frames using Tkinter. In one of the frames I am trying to add a button using a grid. When I run the program, there is no output. Instead it just freezes and I have to kill the process.

Here is the code:

from Tkinter import *
window=Tk()
window.title("calculator")
window.geometry("500x500")
window.resizable(0,0)

input_field=StringVar()
display_frame=Frame(window).pack(side="top")
button_frame=Frame(window).pack(side="bottom")

text=Entry(display_frame,font=('arial',20,'bold'),textvariable=input_field,justify="right").pack(fill="x",ipady=10)
clear_button=Button(button_frame,text="C").grid(row=0)
window.mainloop()

However, if I change the clear_button variable as

clear_button=Button(button_frame,text="C").pack()

I get an output. What am I missing here?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114

2 Answers2

2

You cannot mix grid and pack inside the same container (a Frame/Window).

That said you should realize that your display_frame and button_frame variables are actually None! Why, because Frame(Window) will return a Frame object, but you have applied the pack() function just after that whose return value is None.

So basically the Entry and the Button widgets that you created have master=None and that means they are not inside the Frames that you defined, but actually part of the main Window.

Now you can easily see why clear_button=Button(button_frame,text="C").pack() was working as now the main window has only one geometry manager namely pack.

Here is the working code.

from tkinter import * # "Tkinter" on python 2
window=Tk()
window.title("calculator")
window.geometry("500x500")
window.resizable(0,0)

input_field=StringVar()
display_frame=Frame(window)
display_frame.pack(side="top")
button_frame=Frame(window)
button_frame.pack(side="bottom")

Entry(display_frame,font=('arial',20,'bold'),textvariable=input_field,justify="right").pack(fill="x",ipady=10)
Button(button_frame, text="C").grid(row=0)
window.mainloop()
Miraj50
  • 4,257
  • 1
  • 21
  • 34
0

You cannot use both grid and pack method on widgets having same master.

Here, follow the below thread for a detailed understanding :

python pack() and grid() methods together

Avik
  • 53
  • 10
  • I understand that, I have referred to the calculator program in https://www.datacamp.com/community/tutorials/gui-tkinter-python which also uses grid in pack and runs fine. Any idea on that? – Sidharth Yatish Dec 18 '18 at 05:42