我正在尝试制作一个按钮,如果您单击它会变成紫色,按钮最初是蓝色的,但如果再次单击它会变回蓝色

I am trying to make a button where if you click it it turns purple, button was originally blue, but if clicked again then it turn back to blue

我正在尝试制作一个按钮,如果您单击它,它会变成紫色,按钮最初是蓝色的,这是我制作的。但现在我希望按钮在单击两次或双击时变为蓝色。如何跟踪点击次数?

from tkinter import *
root = Tk()


def click_row_1_B():
    B_bingo_row_1.config(bg="#B900FF")
## if clicked twice :B_bingo_row_1.config(bg="#B900FF")

B_bingo_row_1 = Button(
    root, text="B1", bg="#00CCFF", font=("Helvetica", 20), command=click_row_1_B
)

B_bingo_row_1.grid(row=9, column=1, sticky="nsew")

root.mainloop()

您始终可以将 and 绑定到一个小部件,但具有不同的功能

from tkinter import *
root = Tk()


def click_row_1_B(event):
    B_bingo_row_1.config(bg="#B900FF")
def double_click_row_1_B(event):
    B_bingo_row_1.config(bg="#00CCFF")

B_bingo_row_1 = Button(root, text="B1", bg="#00CCFF", font=("Helvetica", 20))
B_bingo_row_1.grid(row=9, column=1, sticky="nsew")

B_bingo_row_1.bind('<Double-Button-1>', double_click_row_1_B)
B_bingo_row_1.bind('<Button-1>', click_row_1_B)

root.mainloop()

对于每个小部件,可以将 Python 函数和方法绑定到一个事件。

widget.bind(event, handler)

当鼠标指针悬停在小部件上时按下鼠标按钮。详细信息部分指定哪个按钮,例如鼠标左键由事件 Button-1 定义,中间按钮由 Button-2 定义,最右边的鼠标按钮由 Button-3.

Button-4 定义带有滚轮支持的鼠标的向上滚动事件和 Button-5 向下滚动。

类似于 Button 事件,见上文,但按钮是双击而不是单击。要指定鼠标左键、中键或右键,请使用 Double-Button-1Double-Button-2Double-Button-3分别.

这处理了对多次单击的计数并基于此执行某些操作 - 不使用双击处理程序进行快速双击 - 请参阅

函数只是其他对象,您可以向它们添加属性:

  • 在函数中存储颜色列表
  • 存储函数点击次数
  • 点击增加数量
  • 在函数内处理颜色变化
from tkinter import *
root = Tk()


def click_row_1_B():
    """Provide a fancy multicolored button click handler that
    chages backgroundcolor based on clicks and an assigned color list"""
    # increase the click count
    click_row_1_B.click += 1

    # lengths of color list
    colorLen = len(click_row_1_B.colors)

    # set background to "click % colorLen" index in color list
    B_bingo_row_1.config(bg = click_row_1_B.colors[click_row_1_B.click % colorLen])

# put properties on the function - do it before you use them (avoid NameError)
# colors will be cycled in order with each click, wrapping around
click_row_1_B.click = 0    
click_row_1_B.colors = ["#00ccff", "#B900ff", "#eee993"]

B_bingo_row_1 = Button(
    root, text = "B1", bg = click_row_1_B.colors[0], # 1st col to start
    font = ("Helvetica", 20), command = click_row_1_B)

B_bingo_row_1.grid(row=9, column=1, sticky="nsew")

root.mainloop()

输出:

start after 1st click after 2nd click after 3rd click