I am creating a simple entry UI to intake 2 text fields and a folder path. I\'m just getting started with tkinter and I can\'t get the browse button to appear next to the en
Question: How to keep tkinter button on same row as label and entry box
To reach this you have to pack
the Entry
and Button
into a own Frame
.
Note: Use always
side=tk.LEFT
to get the widgets in a row.
This example shows a OOP
solution:
Define a class LabelEntry
inherited from tk.Frame
.
class LabelEntry(tk.Frame):
def __init__(self, parent, text, button=None):
super().__init__(parent)
self.pack(fill=tk.X)
lbl = tk.Label(self, text=text, width=14, anchor='w')
lbl.pack(side=tk.LEFT, padx=5, pady=5)
Condition: If a Button
passed, create a new Frame
to pack
the Entry
and Button
.
if button:
frame2 = tk.Frame(self)
frame2.pack(side=tk.LEFT, expand=True)
entry = tk.Entry(frame2)
entry.pack(side=tk.LEFT, fill=tk.X, padx=5)
button.pack(in_=frame2, side=tk.LEFT, padx=5, pady=5)
else:
entry = tk.Entry(self)
entry.pack(side=tk.LEFT, fill=tk.X, padx=5)
Usage:
Define a class App
inherit from tk.Tk
.
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Helper")
frame = tk.Frame(self)
frame.grid(row=0, column=0)
Loop the fields
and create a LabelEntry
object
entries = []
for field in 'Version', 'Database Name', 'CSV File':
if field == 'CSV File':
button = tk.Button(text="Browse", command=self.callback)
entries.append(LabelEntry(frame, field, button))
else:
entries.append(LabelEntry(frame, field))
Run the Application.
if __name__ == "__main__":
App().mainloop()
Tested with Python: 3.5