【问题标题】:Selfcreating buttons in tkinter python 3 [duplicate]tkinter python 3中的自创按钮[重复]
【发布时间】:2020-06-17 09:59:08
【问题描述】:

我的 tkinter 代码有问题。这就是我到目前为止得到的:

from tkinter import *

root = Tk()



def create_button():
        liste = [['Name 1', 'Name 2', 'Name 3'], ['Name 4', 'Name 5', 'Name 6']]

        #giving any button a diffrent command by changing the 'group'-parameter from the function show_player
        for i in range(len(liste)):
            Button_name = 'Group ' + str(i+1)
            Button(root, text = Button_name, bg = 'white', command= lambda:[show_player(liste, i)]).pack()

def show_player(list1, group):

    for name in list1[group]:
        Label(root, text = name).pack() 

create_button()

root.mainloop()

无论我按下哪个按钮,我都会得到名称“名称 4”、“名称 5”、“名称 6”,

但我希望第一个按钮创建名称为“名称 1”、“名称 2”、“名称 3”的标签

有谁知道为什么它不起作用?

【问题讨论】:

    标签: python button tkinter


    【解决方案1】:

    它不起作用,因为 i 将取其最后一个值 1,用于您创建的所有 lambdas,因为函数体在您调用它之前不会执行。你可以将i作为参数传递给lambda来解决这个问题:

    command=lambda i=i:[show_player(liste, i)]
    

    或者你可以使用partial:

    from functools import partial
    ...
    
    command=partial(show_player, liste, i)
    

    【讨论】:

    • 谢谢哥们。你真的帮助了我^^
    猜你喜欢
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多