Search code examples
pythonuser-interfacetkinterframe

manage frames in tkinter


maybe it is trivial, but I cannot wrap my head around it. I want use frames to make a gui made of

  • 2 radio buttons on the top (with an output variable)
  • n var fields in the middle (with each variable coming out from the gui)
  • 2 radio button at the bottom

I have tried this but I cannot figure it out

import tkinter as tk
from tkinter import ttk


# -----function definition--------------------------------

# define a variable entry
def create_input_field(container, label_set):
    r = 0
    out = []
    for label in label_set:
        ttk.Label(text=label, relief=tk.RIDGE, width=15).grid(row=r, column=0)  # sticky=tk.W)
        var = ttk.Entry(text=label, textvariable=label, width=10).grid(row=r, column=1)
        out.append(var)
        r = r + 1
    return out


# define radio button for output
def create_radio_button_analysis(container):
    selected_size = tk.StringVar()
    sizes = (('uniform', 'u'),
             ('non uniform', 'nu'))

    label = ttk.Label(text="type of analysis")
    # label.pack(fill='x', padx=5, pady=5)
    for size in sizes:
        r = ttk.Radiobutton(container, text=size[0], value=size[1], variable=selected_size)
        r.grid(row=1, column=0)


if __name__ == "__main__":
    # define main window
    root = tk.Tk()
    root.title('Name window')

    frame = ttk.Frame(root)
    frame.rowconfigure(0, weight=1)
    frame.rowconfigure(0, weight=1)
    frame.rowconfigure(0, weight=1)

    # input variables
    variables = ['var_1 (unit of measure)', 'var_2 (unit of measure)', 'var_3 (unit of measure)']
    create_input_field(root, variables)

    create_radio_button_analysis(root)

    root.mainloop()

Solution

  • Here is how you can do that simply using .pack() layout manager:

    from tkinter import Tk, Frame, Radiobutton, Entry
    
    
    root = Tk()
    
    frame_top = Frame(root)
    frame_middle = Frame(root)
    frame_bottom = Frame(root)
    
    frame_top.pack()
    frame_middle.pack()
    frame_bottom.pack()
    
    Radiobutton(frame_top, text='Radio 1 top').pack()
    Radiobutton(frame_top, text='Radio 2 top').pack()
    
    entry_lst = []
    for _ in range(5):
        e = Entry(frame_middle)
        e.pack()
        entry_lst.append(e)
    
    Radiobutton(frame_bottom, text='Radio 1 bottom').pack()
    Radiobutton(frame_bottom, text='Radio 2 bottom').pack()
    
    root.mainloop()