D
D
Durilka962021-12-30 20:21:17
Python
Durilka96, 2021-12-30 20:21:17

How to find index of dynamic tkinter widget?

I create several frames on the form, how can I find out the index of what is necessary for the button to perform the necessary action in the necessary widgets? looks like this ..
61cde9f8ca943607014730.png
how to write the code so that the desired button deletes or takes data from the necessary edit?
code like this to create

def test_dinamic():
    global widgets
    global frames
    doth=tix.Tk()
    frames = []
    widgets = []
    for i in range(2):
        frame = Frame(doth, borderwidth=2, relief="groove")
        frames.append(frame)
        frame.pack(side="top", fill="x")
        for i in range(3):
            widget = Entry(frame)
            widgets.append(widget)
            widget.pack(side="left")
        buttonFrame_update=Button(frame,text="Добавить", command=update_main_db)
        buttonFrame_update.pack(side="right")
        buttonFrame_update = Button(frame, text="Удалить", command=delet_frame)
        buttonFrame_update.pack(side="right")

    doth.mainloop()

def update_main_db():
    global widgets
    print(widgets[0].get())

def delet_frame():
    global frames
    frames[0].destroy()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-12-30
@Durilka96

There are two approaches. One is based on lambdas:

for i in range(2):
    buttonFrame_update=Button(frame,text="Добавить", command= lambda arg=i: update_main_db(arg))

The trick with the lambda argument is necessary to save the current value of i - otherwise, at the moment the lambda is called, it will read the last value of i, and it will point to the last line.
The second way I would choose is to write my own widget - a table row. Then the button click handler will be able to take data from the instance variable.
class MyTableRow(Frame):
    def __init__(self, master, *args, **kwargs):
        super().__init__(master, *args, **kwargs)
        self.widgets = []
        for i in range(3):
            widget = Entry(frame)
            widget.pack(side="left")
            self.widgets.append(widget)
        self.update_btn = Button(self, text = "Добавить", command = self.update_clicked)
        self.update_btn.pack(side="right")
        self.delete_btn = Button(self, text = "Удалить", command = self.delete_clicked)
        self.delete_btn.pack(side="right")
  
    def update_clicked(self):
        print(self.widgets[0].get())
    
    def delete_clicked(self):
        print("whatever")


for i in range(2):
    item = MyTableRow(doth, borderwidth=2, relief="groove")
    frames.append(item)
    item.pack(side="top", fill="x")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question