Tkinter - 多个按钮的相同事件

时间:2016-02-18 01:09:59

标签: events tkinter

使用Tkinter,我有很多按钮。我希望每次按下任何按钮时都会触发相同的回调函数。如何找出按下了哪个按钮?

def call(p1):
    # Which Button was pressed?
    pass

for i in range (50):
    B1 = Button(master, text = '...', width = 2)
    B1.grid(row = i*20, column = 60)               
    B1.bind('<Button-1>',call)

    B2 = Button(master, text = '...', width = 2)
    B2.grid(row = i*20, column = 60)               
    B2.bind('<Button-1>',call)

4 个答案:

答案 0 :(得分:4)

使用列表引用动态创建的按钮,使用lambda存储对按钮对象索引的引用。您可以确定单击了哪个按钮。在下面的示例中,我在按钮对象上使用.cget("text")来演示访问按钮小部件。

import tkinter as tk

root = tk.Tk()
root.minsize(200, 200)

btn_list = [] # List to hold the button objects

def onClick(idx):
    print(idx) # Print the index value
    print(btn_list[idx].cget("text")) #Print the text for the selected button

for i in range(10):
    # Lambda command to hold reference to the index matched with range value
    b = tk.Button(root, text = 'Button #%s' % i, command = lambda idx = i: onClick(idx))
    b.grid(row = i, column = 0)

    btn_list.append(b) # Append the button to a list

root.mainloop()

或者,您可以使用bind,然后从生成的事件对象访问窗口小部件。

import tkinter as tk

root = tk.Tk()
root.minsize(200, 200)

def onClick(event):
    btn = event.widget # event.widget is the widget that called the event
    print(btn.cget("text")) #Print the text for the selected button

for i in range(10):
    b = tk.Button(root, text = 'Button #%s' % i)
    b.grid(row = i, column = 0)
    # Bind to left click which generates an event object
    b.bind("<Button-1>", onClick)

root.mainloop()

答案 1 :(得分:1)

  1. @Steven Summers的第一个例子对我来说似乎最清楚,但我认为没有这个清单就更清楚了。
  2. 我理解这个问题的方式,你不仅想知道点击了哪个按钮,而且希望每个按钮调用另一个未描述的功能(universal在我的下面示例中)。在这种情况下,您可以使用非常方便 combine_funcs(请参阅:Have multiple commands when button is pressed)从一个小部件调用两个函数。
  3. 这是我的代码。而不是列表,我只需要一个字符串,每次点击都会更改和打印。

    import tkinter as tk
    
    root = tk.Tk()
    root.minsize(200, 200)
    
    buttonVal = ''                             
    
    def combine_funcs(*funcs):
        def combined_func(*args, **kwargs):
            for f in funcs:
                f(*args, **kwargs)
        return combined_func
    
    def universal():
        print 'Universal function is called'    
    
    def button_check(buttonName):
        buttonVal = buttonName
        print buttonVal   # Or whatever you want to do with the button info
    
    for i in range(10):
        B1 = tk.Button(root, text = 'Button #%s' % i, command = combine_funcs(universal, lambda buttonName = 'Button #%s' % i:button_check(buttonName)))
        B1.grid(row = i, column = 0)
    
    root.mainloop()
    

答案 2 :(得分:0)

使用lambda

B1 = Button(master, text = '...', width = 2, command = lambda: call('B1') )

等等......

答案 3 :(得分:-1)

这可能不是最简单的解决方案,但它是我能想到的唯一解决方案。

// PostSummmaryView.js
import React from 'react'
import moment from 'moment'

function PostSummaryView (props) {
  const {
    post,
    isLoading,
    isEditing,
    handleOnEdit,
    handleOnCancel,
    handleOnSubmit
  } = props

  const formId = 'editPostForm'

  return (
    isLoading
      ? <div>Loading...</div>
      : <div className='row'>
          {isEditing && <form id={formId} onSubmit={handleOnSubmit}><input type='text' name='name' /></form>}

          <div className='col-md-6'>
            <img src={post.media.url} className='img-responsive' />
            {isEditing && <input type='file' name='media' form={formId}/>}
          </div>
          <div className='col-md-6'>

            <h1>{post.name}</h1>
            <p>
              {moment(post.publicationDate).format('dddd, MMMM Do')}
            </p>

            <hr />

            <p className='text-left'>
              {post.description || 'Lorem ipsum dolor sit amet, consectetur adipisici elit...'}
            </p>

            {isEditing
              ? <div>
                  <button className='btn btn-lg btn-default' onClick={handleOnCancel}>Cancel</button>
                  <button type='submit' className='btn btn-lg btn-default' form={formId}>Submit</button>
                </div>
              : <button className='btn btn-lg btn-default' onClick={handleOnEdit}>Edit</button>
            }

          </div>
        </div>
  )
}

export default PostSummaryView