如何编写按钮回调?

时间:2012-11-06 12:14:05

标签: python user-interface button callback tkinter

下面是我用来制作按钮的棋盘的代码。

from Tkinter import *

for x in xrange(8):
    for y in xrange(8:
        if((x+y)%2 == 0):
            Button(root, bg="white", width=11, height=5).grid(row=y, column=x)
        else:
            Button(root, bg="black", width=11, height=5).grid(row=y, column=x)

我知道如何为单个按钮创建一个回调函数,但我不知道如何为这64个按钮中的每个按钮实现一个回调函数,这样当按下它们时,它们将返回它们在网格中的位置

3 个答案:

答案 0 :(得分:2)

def callback(event):
   x,y = event.widget.grid_location()

此示例应指向正确的方向。

<强>更新 澄清grid_location的用法我做了一个快速谷歌,发现... SO-post ;-) 通过更直接way提供您所需的解决方案让我感到羞耻:

grid_info = event.widget.grid_info()
print "row:", grid_info["row"], "column:", grid_info["column"]

因此应归功于Bryan Oakley ;-)而这个问题可能被称为重复......

答案 1 :(得分:1)

尝试将每个按钮的x和y值绑定到lambda,该lambda可以在按下按钮时调用处理函数。现在你按下每个按钮的x和y位置。

def handlebuttonpress(x,y):
  print 'Button x-{0} y-{1} pressed'.format(x,y)

width, height = 8, 8
for x in xrange(width):
  for y in xrange(height):
    if((x+y)%2 == 0):
        Button(root, command=lambda x=x, y=y: handlebuttonpress(x,y), bg="white", width=11, height=5).grid(row=y, column=x)
    else:
        Button(root, command=lambda x=x, y=y: handlebuttonpress(x,y), bg="black", width=11, height=5).grid(row=y, column=x)

答案 2 :(得分:0)

编辑:我认为我更喜欢@DonQuestion基于事件的方法,因为它不需要为每个按钮使用不同的功能。

下面我修改了原始代码以使用

    master.bind("<Button-1>", self.onclick)

对鼠标点击做出反应(而不是使用tk.Button(command = ...)


import Tkinter as tk

class ButtonEventBlock(object):
    # http://stackoverflow.com/a/6102759/190597
    def __init__(self, master, names, cols):
        self.names = names
        self.cols = cols
        self.button = []
        for i, name in enumerate(names):
            self.button.append(tk.Button(master, text = name))
            row, col = divmod(i, self.cols)
            self.button[i].grid(sticky = tk.W+tk.E+tk.N+tk.S,
                                row = row, column = col, padx = 1, pady = 1)
        master.bind("<Button-1>", self.onclick)

    def onclick(self, event):
        info = event.widget.grid_info()        
        # print(info)
        # {'rowspan': '1', 'column': '3', 'sticky': 'nesw', 'ipady': '0', 'ipadx':
        # '0', 'columnspan': '1', 'in': <Tkinter.Tk instance at 0xab3d7ec>,
        # 'pady': '1', 'padx': '1', 'row': '0'}
        row, col = [int(info[key]) for key in ['row', 'column']]
        i = self.cols*row + col
        print(row, col, self.names[i])

names = ('One', 'Two', 'Three', 'Four', 'Five',
         'Six', 'Seven', 'Eight', 'Nine', 'Ten')

root = tk.Tk()
ButtonEventBlock(root, names, cols = 5)
root.mainloop()

enter image description here