user4607976
user4607976

Reputation:

Using a def() to create mutiple buttons, but commands do not work in tkinter, issue

Every time I do this it creates the buttons automatically but it will not execute the command when the button is pressed, is it possible, and if so how do I do it?

from tkinter import *



class MainWindow():

 def __init__(self):
    def printing():
        print("This is going to print:", i)
    def ButtMaker1(frame1,title,CMDVar,xLoc,yLoc):
        print(title,xLoc,yLoc)
        Title = title
        cmdVar = CMDVar()
        FrameAnchor = frame1
        NewButton = Button(FrameAnchor, text = Title, command = cmdVar)
        NewButton.grid(row = xLoc, column = yLoc)
    window = Tk()
    frame1 = Frame(window)
    frame1.grid(row =1, column = 1)
    for i in range(10):
            print(i)
            title = ("Bob is :" + str(i))
            xLoc = i
            yLoc = i + 1
            CMDVar = printing
            ButtMaker1(frame1,title,CMDVar,xLoc,yLoc)





    window.mainloop()

<MainWindow()

Upvotes: 0

Views: 59

Answers (1)

Novel
Novel

Reputation: 13729

You need to use functools.partial to create functions on the fly (well, there are other ways, but partial is by far the best).

from functools import partial

def printing(i):
    print("This is going to print:", i)

class MainWindow():
    def __init__(self):
        window = Tk()
        frame1 = Frame(window)
        frame1.grid(row =1, column = 1)
        for i in range(10):
            print(i)
            title = ("Bob is :" + str(i))
            xLoc = i
            yLoc = i + 1
            cmdVar = partial(printing, i)
            NewButton = Button(frame1, text = title, command = cmdVar)
            NewButton.grid(row = xLoc, column = yLoc)    

Also, don't nest functions.

Upvotes: 1

Related Questions