How to keep tkinter button on same row as label and entry box

后端 未结 1 1723
予麋鹿
予麋鹿 2020-11-29 13:55

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

相关标签:
1条回答
  • 2020-11-29 14:33

    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

    0 讨论(0)
提交回复
热议问题