Tkinter dynamically create widgets from button

后端 未结 2 1319
日久生厌
日久生厌 2021-01-29 06:40

I\'m attempting to make a dynamic GUI where clicking a button causes the creation of a new frame that is placed above the button with 3 entry widgets (user options) inside of it

2条回答
  •  心在旅途
    2021-01-29 07:02

    This is relatively simple.

    We can do this by creating a Frame widget but not packing it, filling it with whatever we need and then having a Button call the pack on the Frame widget.

    Much like the below:

    from tkinter import *
    
    class App:
        def __init__(self, root):
            self.root = root
            self.create = Button(self.root, text="Create", command=self.draw)
            self.create.pack(side="bottom")
            self.frame = Frame(self.root)
            self.entry1 = Entry(self.frame)
            self.entry2 = Entry(self.frame)
            self.entry3 = Entry(self.frame)
            self.entry1.pack()
            self.entry2.pack()
            self.entry3.pack()
            self.submit = Button(self.frame, text="Submit", command=self.command)
            self.submit.pack()
        def draw(self):
            self.frame.pack(side="top")
        def command(self):
            print(self.entry1.get())
            print(self.entry2.get())
            print(self.entry3.get())
    
    root = Tk()
    App(root)
    root.mainloop()
    

    If you need to add multiple of these forms you can do something like the below which makes use of anonymous functions (lambda) in order to have "self aware" buttons which "know" which frame they're in:

    from tkinter import *
    
    class App:
        def __init__(self, root):
            self.frames = []
            self.entries = []
            self.count = 0
            self.root = root
            self.create = Button(self.root, text="Create", command=self.draw)
            self.create.pack(side="bottom")
        def draw(self):
            self.frames.append(Frame(self.root, borderwidth=1, relief="solid"))
            self.frames[self.count].pack(side="top")
            self.entries.append([Entry(self.frames[self.count]), Entry(self.frames[self.count]), Entry(self.frames[self.count])])
            for i in self.entries[self.count]:
                i.pack()
            Button(self.frames[self.count], text="Submit", command=lambda c=self.count: self.submit(c)).pack()
            self.count += 1
        def submit(self, c):
            for i in self.entries[c]:
                print(i.get())
    
    root = Tk()
    App(root)
    root.mainloop()
    

提交回复
热议问题