Creating elements by loop Tkinter

2020-08-04 05:06发布

问题:

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.

回答1:

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()


回答2:

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)