1

In Tkinter, how would look like the code of button that adds a widget when clicked, infinitely if necessary?

Thanks and sorry for bad english.

2 Answers 2

3

This is a more "classy" version:

from Tkinter import *

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.number = 0
        self.widgets = []
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.cloneButton = Button ( self, text='Clone', command=self.clone)
        self.cloneButton.grid()

    def clone(self):
        widget = Label(self, text='label #%s' % self.number)
        widget.grid()
        self.widgets.append(widget)
        self.number += 1


if __name__ == "__main__":
    app = Application()
    app.master.title("Sample application")
    app.mainloop()

enter image description here

Note you keep your widgets in self.widgets list, so you can recall them and modify them if you like.

Sign up to request clarification or add additional context in comments.

1 Comment

How I would add new widgets in a TopLevel?
1

Well it could look something like this (it could look like a lot of different things):

import Tkinter as tk
root = tk.Tk()
count = 0
def add_line():
    global count
    count += 1
    tk.Label(text='Label %d' % count).pack()
tk.Button(root, text="Hello World", command=add_line).pack()
root.mainloop()

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.