首页 > 解决方案 > 用 tkinter 和 for.. 创建按钮如何知道点击了哪一个?

问题描述

我创建了一个命令,它读取文本文件的元素,并为该文本文件中的每个元素创建一个按钮。

for element in myfile:
 button=Button(root, text="hi").pack()

我想为每个按钮分配一个特定的值(比如如果我按下一个特定的按钮会出现一些东西),但是我为每个按钮得到相同的命令......我该怎么做?

标签: pythontkinter

解决方案


我不确定您在链接的答案中不理解什么。这里有两个可以尝试的工作示例。

import tkinter as tk

root = tk.Tk()

label = tk.Label( root, text = ' Nothing Clicked Yet ')

def button_cmd( obj ):
    label.config( text = obj.cget("text" ) + " clicked." ) 

for ix, caption in enumerate([ 'Button A', 'Button B', 'Button C' ]):
    button = tk.Button( root, text = caption )  # Create the button object
    
    button.config( command = lambda obj = button:  button_cmd( obj ) )
    # Configure the command option. This must be done after the button is 
    # created or button will be the previous button. 
    
    button.pack()

label.pack()

root.mainloop()

不使用 lambda 创建闭包的另一种方法。

root = tk.Tk()

label = tk.Label( root, text = ' Nothing Clicked Yet ')

def make_button_cmd( obj ): 
    # This returns a function bound to the obj
    def func():
        label.config( text = obj.cget("text" ) + " clicked." ) 

    return func

for ix, caption in enumerate([ 'Button A', 'Button B', 'Button C' ]):
    button = tk.Button( root, text = caption )  # Create the button object
    
    button.config( command = make_button_cmd( button ) )
    # Configure the command option. This must be done after the button is 
    # created or button will be the previous button. 
    
    button.pack()

label.pack()

root.mainloop()

推荐阅读