从条目、组合框、文本中获取值的通用函数

Universal function to get the value from a entry, combobox, text

是否可以创建一个通用函数来从条目中获取值?

像这样:

def returnInput(obj):
    _x = StringVar()
    obj.configure(textvariable=_x)
    return str(_x.get())

感谢帮助

对于大多数 tkinter 文本函数,var = obj.get() 最常用,但有一些例外。

例如:

entry.get()
listbox.get(listbox.curselection())

或为组合框导出选择。

使用这些方法比创建函数要容易得多。

不,不是那样的。但是,您可以定义如下函数:

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