【发布时间】:2017-09-09 14:49:31
【问题描述】:
我想在按钮的命令中使用从列表框中选择的值,这样在按下“开始”按钮之前不会执行任何代码。
到目前为止,我只看到列表框通过绑定到 来执行选择元素的代码。这对我来说似乎很愚蠢,当然程序应该有某种两阶段选择,以确保用户选择他们想要的内容(切线,抱歉)。
到目前为止,我已经尝试使用 .curselection()[0] 和 .get 为当前选择创建一个变量,但我得到了一个索引错误(可能是因为最初没有选择)。然后,如果我设置了初始选择,我无法更改它,它将始终基于该选择执行。
当然,这应该很容易,但我错过了一些东西。
[编辑] 按照建议添加代码转储:
class DataVisualiser:
def __init__(self, master):
master.minsize(width=600, height=400)
frame = Frame(master)
frame.grid()
# Histogram Generator
hist_options = ["Cat vs. Dog", "Cat Breed", "Dog Breed", "Cat Name", "Dog Name", "Cat Location",
"Dog Location", "Cat Registration", "Dog Registration"]
hist_dd = Listbox(master, bg="#cfcfcf", fg="black", font="Helvetica", height=5, selectmode=SINGLE)
for o in hist_options:
hist_dd.insert(0, o)
hist_dd.grid(row=0, column=0)
hist_dd.selection_set(first=0)
hist_scroll = Scrollbar(master, orient=VERTICAL)
hist_dd["yscrollcommand"] = hist_scroll.set
hist_scroll["command"] = hist_dd.yview
hist_scroll.grid(row=0, column=1, rowspan=7, sticky=N+S)
# scrollbar from: https://www.youtube.com/watch?v=xNLdB0jY1Rg
# HERE: I want to pass the value from the listbox to another function via this button
hist_gen = Button(master, text="Go!",
command=lambda group=hist_dd.get(hist_dd.curselection()[0]): generate_histogram(group))
# still need to fully implement this
hist_gen.grid(row=6, column=0, sticky=W+E)
def generate_histogram(group):
print(group)
return None
root = Tk()
dv = DataVisualiser(root)
root.mainloop()
【问题讨论】:
-
显示您的代码将对我们所有人都有帮助。请阅读minimal reproducible example。
-
在GO按钮的回调函数中可以直接获取listbox项吗?
-
用什么?正如我所说的
command=lambda group=w.get(w.curselection()[0]): go(group))导致索引错误。