是否有可能使一个有效的通用函数从一个条目中获取值?
像这样的东西:
def returnInput(obj):
_x = StringVar()
obj.configure(textvariable=_x)
return str(_x.get())
谢谢您的帮助
不,不是那样的。但是,您可以定义如下函数:
def uni_get(widget):
wgt_typ = type(widget).__name__
if wgt_typ == 'Label' or wgt_typ == 'Button':
disp_str = widget['text']
elif wgt_typ == 'Text':
disp_str = widget.get('1.0', 'end-1c')
elif wgt_typ == 'Combobox' or wgt_typ == 'Entry':
disp_str = widget.get()
return disp_str
演示示例:
import tkinter as tk
from tkinter import ttk
def uni_get():
#to dynamically update the selected widget passed to uni_get
global cbb
widget = root.winfo_children()[cbb.current()]
wgt_typ = type(widget).__name__
if wgt_typ == 'Label' or wgt_typ == 'Button':
disp_str = widget['text']
elif wgt_typ == 'Text':
disp_str = widget.get('1.0', 'end-1c')
elif wgt_typ == 'Combobox' or wgt_typ == 'Entry':
disp_str = widget.get()
print(disp_str)
root = tk.Tk()
cbb = ttk.Combobox(root)
ent = tk.Entry(root)
txt = tk.Text(root)
lbl = tk.Label(root)
btn = tk.Button(root, command=uni_get)
### default widget configs ###
cbb['values'] = ["Combobox", "Entry", "Text", "Label", "Button"]
cbb.current(0)
ent.insert('0', "Entry")
txt.insert('1.0', "Text")
lbl['text'] = "Label"
btn['text'] = "Button"
### layout ###
cbb.pack()
ent.pack()
txt.pack()
lbl.pack()
btn.pack()
root.mainloop()
对于大多数tkinter文本函数,var = obj.get()最常用,但有一些例外。
例如:
entry.get()
listbox.get(listbox.curselection())
或组合框的导出选择。
使用这些方法比创建函数要容易得多。