问题是使用def()创建多个按钮,但命令在tkinter中不起作用

时间:2017-03-05 16:51:40

标签: python button tkinter

每次我这样做都会自动创建按钮但按下按钮时不会执行命令,是否可能,如果可以,我该怎么做?

var dlcNameList = ['they shall not pass', 'in the name of the tsar', 'apocalypse'],
    dlcReleaseDate = [new Date(2017,2,28), new Date(2017,6,15), new Date(2017,11,25)],
    result = [];
    
    dlcNameList.forEach((v,i) => result.push({name : v, date : dlcReleaseDate[i]}));
    console.log(result);

1 个答案:

答案 0 :(得分:2)

你需要使用functools.partial动态创建函数(嗯,还有其他方法,但partial是最好的)。

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)    

另外,不要嵌套功能。