【问题标题】:How to make a tkinter button clickable or not on a given condition如何在给定条件下使 tkinter 按钮可点击或不可点击
【发布时间】:2021-12-11 15:42:11
【问题描述】:

我想渲染 2 个在列表中导航的按钮(下一个和上一个)。而且我希望上一个和下一个按钮处于活动状态(可点击),而不是分别到达列表的开始和结束时。 我该怎么办?

【问题讨论】:

  • 只需根据当前列表索引更改按钮回调中按钮的state 选项。

标签: python tkinter button


【解决方案1】:

这是一个看似简单的问题,实际上需要一些努力来实现。

也许其他人可以找到更优雅的解决方案。

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

【讨论】:

  • 好一个@Yann,编码愉快。
猜你喜欢
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 2015-09-26
  • 2020-01-17
  • 2015-10-05
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
相关资源
最近更新 更多