【问题标题】:Tkinter Button Function [duplicate]Tkinter 按钮功能 [重复]
【发布时间】:2019-03-22 04:30:39
【问题描述】:

我试图在 Tkinter 中使用 GUI 按钮,但在尝试使用它们时遇到了问题。这段代码应该(至少我期望它会)生成一些按钮,当点击这些按钮时,会打印出正在显示的字母。但是,无论按下哪个按钮,它总是会打印出最后生成的按钮的结果。我应该以不同的方式使用这样的功能吗?

import tkinter  

win = tkinter.Tk()
players = ["A","B","C","D"]

for p in players:
    playerBtn = tkinter.Button(win,text=p,command=lambda : print(p))
    playerBtn.pack()

tkinter.mainloop()

【问题讨论】:

    标签: python function tkinter


    【解决方案1】:

    这是因为lambda 只是查找p 的全局值。要改变这一点,我们将执行以下操作 -

    import tkinter  
    
    win = tkinter.Tk()
    players = ["A","B","C","D"]
    
    for p in players:
        player_button = tkinter.Button(win, text=p, command=lambda button_text=p: print(button_text))
        player_button.pack()
    
    tkinter.mainloop()
    

    在 Ubuntu 18.04 上对此进行了测试,它的工作原理与您的需求一样。

    您可以参考this SO 帖子了解有关此行为的更多详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 2021-11-07
      • 2020-09-19
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      相关资源
      最近更新 更多