0

After making an array of buttons using tkinter, the buttons are not clickable, almost as if the unique commands I'm assigning each button are not sticking to each button

I've tried using the lambda method and the partial method, but neither seem to work

import tkinter as tk
from functools import partial

#Sets root as Tk
root = Tk()

#Makes our GUI space
canvas = Canvas(root, width = 1600, height = 1100, bg = "white")

class App:

def clicked(self, i):
    print("Clicked")
    print(self.button[i])

def __init__(self, root): 

    self.root = root
    self.button = [];

    #Allows button size to be set in pixels
    pixel = tk.PhotoImage(width=1, height=1, master = root)

    for i in range(5):

       #Makes each button and adds it to self.button array
       self.button.append(tk.Button(root, bg = "red", image=pixel,
                     width = 10, height = 10, 
                     command=lambda: clicked(i)))

       #I have also tried:
       #command=partial(clicked, i)
       #command=lambda i=i: clicked(i)

       #Places button on canvas
       self.button[i].place(x=10*i, y=10*i, in_=canvas)

       canvas.pack()

App(root)
root.mainloop()

I am expecting to be able to click each of these button and see the word "Clicked" appear in the Jupyter terminal line. But I get nothing...

I've looked here and here and a few other places, but I'm still stuck on something...any ideas?

Orange Man
  • 21
  • 3

1 Answers1

0

First, when you're calling clicked(), the interpreter doesn't expect it to be inside the class.

Instead, you should call self.clicked(). When I did that it worked (almost) fine; I got the text in the python shell: "Clicked .!Button5".

The only problem was that every button was button 5, and I think this is to do with the button numbering in the loop. Once you've declared your first button, where i = 1, i changes value as with iterables in for loops.

ofthegoats
  • 295
  • 4
  • 10
  • I changed the `clicked()` to `self.clicked()` and I also tried `self.clicked` but I still can't get the buttons to respond. I literally copy and paste the code from the original question, change the clicked to self.clicked, and still the buttons are useless! – Orange Man Jul 12 '19 at 15:26
  • @OrangeMan I also commented out the declaration for `pixel`, and removed it from the button declaration, assuming that it didn't work due to part of my config. If you're just getting a blank toplevel, try removing that and maybe play around with it at a later date. Otherwise, try running this through Python3's IDLE, since it worked for me there. – ofthegoats Jul 12 '19 at 15:46