你能在tkin中为一个形状添加回调/命令吗

2024-05-16 01:12:58 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我正在尝试在OSX上编写Ultimate Tic-Tac-Toe,我读到here你不能改变OSX上按钮的颜色。这使得GUI看起来像这样。。。 enter image description here

我发现白色的按钮是一个眼中钉,并真正远离游戏 因此,是否可以向一个对象(而不是按钮)添加回调。像这样。。。在

window.create_rectangle(x1,y1,x2,y2,callback = foo)

Tags: 对象游戏here颜色createguiticwindow
3条回答

如果在绘制坐标为(a, b)(c, d)的矩形:

def callback(event):
    if a <= event.x <= c:
        if b <= event.y <= d:
            print 'Rectangle clicked' # change rect here

window.bind('<ButtonPress-1>', callback)

是的,你可以在任何小工具上绑定。一个常见的做法是使用标签小部件,尽管您也可以使用画布绘制任何您想要的形状。如果您使用行和列作为键将所有小部件存储在字典中,那么回调很容易知道您单击了什么(当然,event.widget也会告诉您)。在

下面是一个使用标签的快速示例,并说明如何将行和列传递到回调中。为了简洁起见,它只创建了一个tic-tac脚趾板:

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, background="bisque")
        self.canvas = tk.Canvas(self, width=400, height=400)

        board = TicTacToe(self)
        board.pack(padx=20, pady=20)

class TicTacToe(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, background='black')

        self.player = "X"
        self.cell = {}
        for row in range(3):
            for col in range(3):
                cell = tk.Label(self, background="darkgray", foreground="white", width=2)
                cell.bind("<1>", lambda event, col=col, row=row: self.on_click(row, col))
                cell.grid(row=row, column=col, sticky="nsew", padx=1, pady=1)
                self.cell[(row,col)] = cell

    def on_click(self, row, col):
        current = self.cell[(row, col)].cget("text")
        if current == "X" or current == "O":
            self.bell()
            return
        self.cell[(row, col)].configure(text=self.player)
        self.player = "X" if self.player == "O" else "O"

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

如果rects是一个矩形列表:

rects = [] # contains rects

def callback(event):
    for rect in rects:
        if rect.a <= event.x <= rect.c:
            if rect.b <= event.y <= rect.d:
                rect.change()

window.bind('<ButtonPress-1>', callback)

相关问题 更多 >