0

I am new to Python and coding and i am trying to make an object detection application. For this i have used a loop which will print out buttons for the objects that was detected. For example if we have detected 3 objects, then 3 buttons will appear on a Tkinter window, where by clicking on each will bring you to an amazon page where you can shop for that product.

I managed to complete work with buttons, however when i select a button for the objects detected, it only opens up an amazon page for the last object detected and i assume its because python loop erases previous data and keeps the last one, (if i am right). The problem is based in the commented part of this code, where i need an application to read the URL for all objects and not only last one. I hope it is clear. Here is the code i have used:

def button_window():
    window.geometry("350x600")

    # Create a LabelFrame
    labelframe = LabelFrame(window)

    # Define a canvas in the window
    canvas = Canvas(labelframe)
    canvas.pack(side=RIGHT, fill=BOTH, expand=1)
    labelframe.pack(fill=BOTH, expand=1, padx=30, pady=30)

    start = 0
    end = length_list
    step = 1

    for y in range(start, end, step):
        x = y
        sec = new_lst[x:x+step]

        # URL
        init_url = "amazon.co.uk/s?k="
        x = str(sec)

        final_url = init_url + x
        cutting = final_url.replace("'", '')
        cutting_two = cutting.replace("[", "")
        cutting_three = cutting_two.replace("]", "")

        print(cutting_three)

        # def open():
        #     for x in range(cutting_three):
        #         webbrowser.open(cutting_three)
        

        btn = Button(canvas, text=sec, command=open)
        btn.pack()

    window.mainloop()
JRiggles
  • 4,847
  • 1
  • 12
  • 27
  • Use parameter to the function to pass the link and follow [this](https://stackoverflow.com/questions/10865116/tkinter-creating-buttons-in-for-loop-passing-command-arguments) question. – Delrius Euphoria Jan 27 '23 at 20:01

1 Answers1

0

I beleive the issue is you are assigning the 3 buttons to the same function: open, which is re-defined every time you loop over. Create the function outside the loop. Also open function does not take any input, so for the 3 buttons it will run the same code.

Depending how your program works, try to simplify few things. for instance:

def open(url):
    webbrowser.open(url)

init_url = "amazon.co.uk/s?k="
for item in new_lst:
    final_url = init_url + item
    Button(canvas, text=item, command=lambda url=finla_url: open(url)).pack()

Lambda is necessary to avoid open(url) be called at creation time. Lastly, new_lst variable is probably being taken from the outer scope, so you might want to make it an input parameter to the function (as well as init_url, rather than defining this variable inside the window function)

mamg2909
  • 96
  • 4