开发者

Objects from Tkinter controls: how to go beyond StringVar, IntVar, DoubleVar, BooleanVar?

I'm trying to write a GUI in Tkinter to select one among several complex Python objects. They represent records from a database; if needed, I could recover objects from a map given their integer unique id.

In an ideal world, the Listbox and OptionMenu widgets would accept a sequence of arbitrary objects and a function to call to obtain a string to display from those arbitrary objects; and their variables would give one of those objects, without unwanted conversions.

Instead, no widget and, more crucially, no variable type deals with anything other than strings or strings converted to numbers and truth values. I have no way to get my arbitrary objects back, and I cannot make a list containing id values be开发者_如何学Pythoncause they would display the id, not a sensible string representation.

As a test, I put tuples in an OptionMenu with a StringVar and they were converted to strings.

Are there exotic widgets or techniques that I can use to get() objects from a variable or to show in the widget a string that is not what is put in the widget's variable? The best approach I can think of is a menu full of dynamically generated lambdas for commands, but it would be ugly and potentially too large.


What I did to solve this problem, at least for my ListBox was to have an array which represented all the data in the list. Say that complexobjects is your list of objects,

for obj in complexobjects:
    listbox.insert(END, str(complexobjects))

replace str(complexobjects) with whatever you want your string representation to be. You don't need to store it or look it up, just use the index,

selitems = [complexobjects[int(idx)] for idx in listbox.curselection()]

Read this page, http://effbot.org/tkinterbook/listbox.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜