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.
-
This can be easily done using comprehension lists. However, it can be helpful to post also what have you tried.A. Rodas– A. Rodas2013-03-26 16:21:25 +00:00Commented 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.Arktri– Arktri2013-03-26 16:32:40 +00:00Commented Mar 26, 2013 at 16:32
Add a comment
|
2 Answers
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()