简体   繁体   中英

Tkinter problem with geometry of composite frame

I have a frame with two element in it; namely, an Entry and a Button.

class MyEntry(tk.Frame):
def __init__(self, root, *args, **kwargs):
    super().__init__(root)

    self.var = tk.StringVar(self)
    self.var.trace("w", self.changed)

    self.entry = tk.Entry(self, textvariable=self.var)

    self.button = tk.Button(self, text='▼',command=lambda: self.changed('','','arrow'))

Whenever I try to pack() or place() the frame to the parent widget I always get different things - not what I want.

I want this:

我想要的是

If I use place:

self.entry.place(relx=0,rely=0,relwidth=0.95,relheight=1)
self.button.place(relx=0.95,rely=0,relwidth=0.05,relheight=1)

I get this:

结果与place()

Whereas, if I use pack:

self.entry.pack(side='left')
self.button.pack(side='right')

I get this:

pack()的结果

I use place() for the parent widget. I have tried all combinations of options (fill, expand, propagate etc.) but nothing works!!!

Any help would be much appreciated!

You want to use this:

self.button.pack(side='right')
self.entry.pack(side='left', fill="x", expand=True)

The order is important, as is the fill option for the entry.

If there's not enough space in for the widgets then tkinter will start to shrink widgets in the reverse order that they were packed. In your case you're probably forcing the window to a smaller size than necessary, so tkinter is removing pixels from the button because it was packed last. By packing the entry last, it will shrink or expand as necessary, and it can afford to shrink a lot more than the button before it disappears.

Are you trying to create a combobox? If so, try using a ttk.Combobox instead.

With regard to placing widgets, I recommend using a grid. Personally I tend to make a sketch of a window with the widgets I want to use. Then I draw a grid over that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM