0

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()
1
  • cmdVar = CMDVar() -> cmdVar = CMDVar Commented Mar 5, 2017 at 16:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.