如何在给定条件下使 tkinter 按钮可点击或不可点击
How to make a tkinter button clickable or not on a given condition
我想呈现 2 个按钮(下一个和上一个),它们在列表中导航。我希望上一个和下一个按钮处于活动状态(可单击),而不是分别到达列表的开始和结束时。
我该怎么办?
这是一个看似简单的问题,实际上需要一些努力才能实现。
也许其他人可以找到更优雅的解决方案。
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()
我想呈现 2 个按钮(下一个和上一个),它们在列表中导航。我希望上一个和下一个按钮处于活动状态(可单击),而不是分别到达列表的开始和结束时。 我该怎么办?
这是一个看似简单的问题,实际上需要一些努力才能实现。
也许其他人可以找到更优雅的解决方案。
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()