How do I toggle tkinter button text when right clicked

Question:

I’m trying to get these buttons to toggle the text between "F" and "" when right-clicked. Right now, nothing happens when I right-click on them, not even the little relief animation that normally occurs when a button is pressed. The problem is definitely in my if-elif statement because configuring normally works fine.

from tkinter import *


def play():
    win = Tk()

    main_frame = Frame(win)
    main_frame.pack()

    btn_grid = list()
    i = 0
    for row in range(8):
        for col in range(8):
            btn_grid.append(Button(main_frame, text="", height=1, width=1, font="Verdana", relief='groove'))
            btn_grid[i].grid(row=row, column=col, sticky="news", ipadx=20, ipady=15)
            btn_grid[i].bind("<Button-3>", lambda e, c=i: right(c))
            i = i + 1

    def right(ind):
        if btn_grid[ind].config("text") == "":
            btn_grid[ind].config(text="F")
        elif btn_grid[ind].config("text") == "F":
            btn_grid[ind].config(text="")

    win.mainloop()

play()
Asked By: say

||

Answers:

I needed to use cget() instead of config() to check the text. Changing that makes it work properly!

def right(ind):
    if btn_grid[ind].cget("text") == "":
        btn_grid[ind].config(text="F")
    elif btn_grid[ind].cget("text") == "F":
        btn_grid[ind].config(text="")
Answered By: say

Easier way like this:

code:

def right(ind):
    if btn_grid[ind].cget("text") == "":
        btn_grid[ind].config(text="F")
    else:
        btn_grid[ind].config(text="")
Answered By: toyota Supra
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.