1

I'm looking for a way to create elements dynamically in Tkinter. For example, say the user enters 5, I'd like a loop to create 5 radio buttons and entries next to them.

2
  • This can be easily done using comprehension lists. However, it can be helpful to post also what have you tried. Commented Mar 26, 2013 at 16:21
  • I have yet to code anything because I'm not sure where to start. I think the main issue I am having is dynamically creating variable names. Commented Mar 26, 2013 at 16:32

2 Answers 2

2

Here's a simple example to get you started:

import Tkinter as tk

class ButtonBlock(object):
    def __init__(self, master):
        self.master = master
        self.button = []
        self.button_val = tk.IntVar()
        entry = tk.Entry()
        entry.grid(row=0, column=0)
        entry.bind('<Return>', self.onEnter)
    def onEnter(self, event):
        entry = event.widget
        num = int(entry.get())
        for button in self.button:
            button.destroy()
        for i in range(1, num+1):
            self.button.append(tk.Radiobutton(
                self.master, text=str(i), variable=self.button_val, value=i,
                command=self.onSelect))
            self.button[-1].grid(sticky='WENS', row=i, column=0, padx=1, pady=1)
    def onSelect(self):
        print(self.button_val.get())

if __name__ == '__main__':
    root = tk.Tk()
    ButtonBlock(root)
    root.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

1

There's nothing special about widgets. You create them in a loop the same way you would create any other object:

for i in range(5):
    r = tk.Radiobutton(...)
    r.pack(...) # or .grid(...)

    # if you need to reference these buttons later,
    # save them in a list
    self.buttons.append(r)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.