Home > Net >  How do I toggle tkinter button text when right clicked [ANSWERED]
How do I toggle tkinter button text when right clicked [ANSWERED]

Time:04-15

I figured it out. Stackoverflow says I cant accept my own answer for two days. Just leaving it up in case anyone has the same issue in the future!

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()

CodePudding user response:

Figured it out, 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="")
  • Related