1

In my simple GUI whenever I press the button the text is supposed to be packed inside the frame, but upon pressing the frame disappears.

Here is the code:

import tkinter as tk

window=tk.Tk()
window.geometry('600x600')
window.resizable(False,False)

f1=tk.Frame(window,height=200,width=200,bg='yellow')
f1.place(x=400,y=400)

some=tk.StringVar()
def press():
    msg=some.get()
    l1=tk.Label(f1,text=str(msg))
    l1.pack()

e1=tk.Entry(window,textvariable=some)
e1.pack()
b1=tk.Button(window,text='press',command=press)
b1.pack()

window.mainloop()

The text is packed but the frame disappeared.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    I think it's because you are attempting to use both the `place` and `pack` geometry managers at the same time (and they don't play together well). – martineau Jan 17 '21 at 19:02
  • Place is more precise than pack when comes to complex GUI. So any way to solve this issue? –  Jan 17 '21 at 19:15
  • Use a .place() for l1 instead of .pack() – Zishe Schnitzler Jan 17 '21 at 20:00
  • Personally I use `grid` for 99% of what I do — and have never felling like I'm scarify too much control in so doing. Also, when you use `place` it's very easy to become resolution and/or windows size dependent when you specify positions or dimensions in absolute values instead of relative ones. To solve the issue, I suggest you pick one manager and stick with it at least inside each frame. – martineau Jan 17 '21 at 20:01

1 Answers1

1

This happens because Frame adjusting its size according to contents inside. At the beginning Frame keeping size that was defined during initialization, but when you add label it resizes to dimensions of content. To disable this behaviour you need to add f1.pack_propagate(0)

Second thing is that background around added text will be not yellow, so you also need to add it to arguments: l1=tk.Label(f1,text=str(msg),bg='yellow')

After applaying those changes it will work but, as mentioned, it's not desirable to use place and pack in one window. It's unpredictable. So my final version looks like this:

import tkinter as tk

window=tk.Tk()
window.geometry('600x600')
window.resizable(False,False)


some=tk.StringVar()
def press():
    msg=some.get()
    l1=tk.Label(f1,text=str(msg),bg='yellow')
    l1.pack(anchor="w")

e1=tk.Entry(window,textvariable=some)
e1.pack()
b1=tk.Button(window,text='press',command=press)
b1.pack()

f1=tk.Frame(window,height=200,width=200,bg='yellow')
f1.pack(anchor="se")
f1.pack_propagate(0)

window.mainloop()
andrewf1
  • 61
  • 4