如何高效存储Tkinter控件值?三类控件使用疑问咨询
Tkinter控件值获取与存储问题
以下是我编写的测试代码:
from tkinter import* window= Tk() window.geometry("300x300") #1) def getEntry(): result= a.get() print(result) a = Spinbox(window, from_=0, to=10, command=getEntry) a.pack() #2) def getEntry2(): result=s.get() return result s = Spinbox(window, from_=0, to=10, command=getEntry2) print(s) s.pack() #3) def getEntry3(): result=Trees.get() print(result) Trees= Listbox(window, command=getEntry3) Trees.insert(1, "Tree1") Trees.insert(2, "Tree2") Trees.pack() bouton_close= Button(window, text="Fermer", command=window.quit) bouton_close.pack() window.mainloop()
疑问:
- 为什么每次获取结果都要创建不同的函数?这种重复定义相似功能函数的方式不够高效,能否简化代码?为何无法使用如下方式:
def getEntry(name): result=name.get() print(result) a = Spinbox(window, from_=0, to=10, command=getEntry(a))
- 能否存储控件的值?我可以在getEntry中打印值,但在getEntry2中返回值时无报错却没有输出。
- 为何Listbox使用command选项时提示"unknown option "-command"",该选项不被识别?
解答:
1. 简化重复函数的方法
你不能直接用command=getEntry(a)是因为这样写会立即执行函数,而不是把函数绑定为回调。Tkinter的command参数需要接收一个无参数的可调用对象。要复用函数,可以用lambda表达式或者functools.partial来传递控件对象:
用lambda的示例:
def get_entry(widget): print(widget.get()) a = Spinbox(window, from_=0, to=10, command=lambda: get_entry(a)) a.pack() s = Spinbox(window, from_=0, to=10, command=lambda: get_entry(s)) s.pack()
这样就不用重复定义多个功能一样的函数了。
2. 存储控件的值
getEntry2里返回的值没输出,是因为Tkinter会忽略回调函数的返回值。要存储值,你可以用全局变量、类属性,或者专门的存储容器:
比如用全局变量:
stored_value = None def getEntry2(): global stored_value stored_value = s.get() print(f"已存储值: {stored_value}") s = Spinbox(window, from_=0, to=10, command=getEntry2) s.pack()
之后在其他地方就能直接用stored_value获取存储的内容了。大型项目更推荐用类来管理控件和数据,避免全局变量混乱。
3. Listbox没有command选项
Tkinter的Listbox控件本身就不支持command参数。要监听Listbox的选择变化,需要绑定<<ListboxSelect>>事件:
示例代码:
def getEntry3(event): selected_indices = Trees.curselection() if selected_indices: result = Trees.get(selected_indices[0]) print(result) Trees = Listbox(window) Trees.insert(1, "Tree1") Trees.insert(2, "Tree2") Trees.bind('<<ListboxSelect>>', getEntry3) Trees.pack()
注意curselection()返回的是选中项的索引元组,需要先判断是否有选中项,再去获取对应的值,避免索引越界错误。
内容的提问来源于stack exchange,提问作者evamaaz
相关产品推荐
相关产品推荐

