Home > Software engineering >  How to make a tkinter button clickable or not on a given condition
How to make a tkinter button clickable or not on a given condition

Time:10-28

I want to render 2 buttons (next and previous) that navigates trough a list. And I want the prev and next buttons to be active(clickable) and not when the start and the end of the list are reached respectively. How can i do ?

CodePudding user response:

This is a deceptively simple question that actually requires some effort to implement.

Perhaps someone else can find a more elegant solution.

import tkinter as tk

data = ["A", "B", "C"]

def pickfrom(A, B):
    end = listbox.index(tk.END) - 1
    selection = listbox.curselection()[0]
    listbox.select_clear(0, end)
    if A == Next:
        selection = selection   1
        if selection >= end:
            A.config(state = "disabled", text = "")
            selection = end
        B.config(state = "normal", text = "◀")
    else:
        selection = selection - 1
        if selection <= 0:
            A.config(state = "disabled", text = "")
            selection = 0
        B.config(state = "normal", text = "▶")
    listbox.select_set(selection)
    return listbox.get(selection)

def back():
    print(pickfrom(Prev, Next))

def fore():
    print(pickfrom(Next, Prev))

master = tk.Tk()
listdata = tk.StringVar(master, value = data)
listbox = tk.Listbox(
    master, listvariable = listdata, activestyle = tk.NONE,
    selectmode = "browse", takefocus = 0)
listbox.grid(row = 0, column = 0, columnspan = 2, sticky = tk.NSEW)
listbox.select_set(0)

Prev = tk.Button(master, text = "◀", command = back)
Prev.grid(row = 1, column = 0, sticky = tk.EW)
Next = tk.Button(master, text = "▶", command = fore)
Next.grid(row = 1, column = 1, sticky = tk.EW)
master.mainloop()
  • Related