-1

How can I set it so that all 10 buttons each have a different command using this code:

line1 = ['q','w','e','r','t','y','u','i','o','p']

for n in range(10):
        tkinter.Button(keyboard, text = line1[n], command = line1[n]).grid(column = n + 1, row = 0, padx = 1, pady = 1)

Current Code:

line1 = ['q','w','e','r','t','y','u','i','o','p']

functions = [lambda: q(), lambda: w(), lambda: e(), lambda: r(), lambda: t(), lambda: y(), lambda: u(), lambda: i(), lambda: o(), lambda: p()]
    buttons = []
    def q():
        buttons[0].destroy()
    def selectCallback(n):
        global functions
        global buttons
        if n > 1:
            functions[2](n)
        else:
            functions[n]()
    for n in range(10):
        buttons.append(tkinter.Button(keyboard, text = line1[n], command = lambda n = n: selectCallback(n)))
        buttons[n].grid(column = n + 1, row = 0, padx = 1, pady = 1)

When this is run it causes the error.

1 Answers1

0

A callback for callbacks!

Probably not the most elegant solution but you can have one main function which decides which function to use based on the argument given by the button.

You will need to decide what each value of n will call.

EDIT: Changed code answer comment

import Tkinter

keyboard = Tkinter.Tk()
line1 = ['q','w','e','r','t','y','u','i','o','p']
buttons = []
def func0():

    print("This could be 0's function")
    buttons[0].destroy()

def func1():

    print("This could be 1's function")
    buttons[1].destroy()

def funcX(n):


    print("You get the idea...")
    buttons[n].destroy()

functions = [lambda: func0(), lambda: func1(), lambda n: funcX(n)]

def selectCallback(n):

    global functions
    global buttons
    # If `functions` is filled out for all elements you can neglect this 
    # if/else and simply call `functions[n]()`
    if n > 1:
        functions[2](n)
    else:
        functions[n]()

for n in range(10):
        buttons.append(Tkinter.Button(keyboard, text = line1[n], command = lambda n = n: selectCallback(n)))
        buttons[n].grid(column = n + 1, row = 0, padx = 1, pady = 1)

keyboard.mainloop()

Important points:

-Must keep a reference to the buttons to be able to delete them (buttons)

-Must call .grid() on a separate line so it does not return None for what should be the Button.

-If all you want to do is delete the buttons, this does not require a different function for each. This example is meant to illustrate how you could have 10 different functions as callbacks.

-Additionally, my example is simplified: for buttons [2:9] I only call one function and pass an index so that I don't have to write out 10 functions. If you want to do a different function that performs a different operation for each button, fill out the functions list properly and remove the if/else construct within selectCallback(n), and access each function directly by its index.

maccartm
  • 2,035
  • 14
  • 23