Wouter Wouter - 5 months ago 10
Python Question

Variable input Python

I've made a simple GUI in Tkinter.(Code is below)
When I press the "Fetch" botton than I get the text input from the GUI in a Command line.

Let's say that in this example the "user" is putting 0.5 in the "Service Points Won" field and 0.7 in the " Return Points Won" field as input.
When I press the "Fetch" botton I get the following results displayed in command prompt

0.5
0.7


What I would like to achieve is that next to the displayed result in command prompt the matching "Label" is also displayed.

So to return to my example with 0.5 and 0.7 as input. I want to get a result in command prompt as followed.

"Service Points Won" 0.5
"Return Points Won" 0.7



GUI Script


from Tkinter import *

fields = 'Service Points Won', 'Return Points Won'

def fetch(variables):
for variable in variables:
print "%s" % variable.get()

def makeform(root, fields):
lab1= Label(text="Stats", font="Verdana 10 bold")
form = Frame(root)
left = Frame(form)
rite = Frame(form)
lab1.pack(side=TOP)
form.pack(fill=X)
left.pack(side=LEFT)
rite.pack(side=RIGHT)

variables = []
for field in fields:
lab1= Label()
lab = Label(left, text=field)
ent = Entry(rite)
lab.pack(anchor='w')
ent.pack(fill=X)
var = StringVar()
ent.config(textvariable=var)
var.set('0.5')
variables.append(var)
return variables

if __name__ == '__main__':
root = Tk()
vars = makeform(root, fields)
Button(root, text='Fetch',
command=(lambda v=vars: fetch(v))).pack()
root.bind('<Return>', (lambda event, v=vars: fetch(v)))
root.mainloop()


Any suggestions?

Answer

Since you want to map some fields to others, using a dictionary is a better choice than using a list.

def fetch(variables):
    for key, val in variables.items():
        print key, val.get()

def makeform(root, fields):
    ...
    variables = {}
    for field in fields:
        ...
        variables[field] = var #associate a field with its variable
    return variables

Which will print out

Service Points Won 0.5
Return Points Won 0.7

Note that you can format your print as you wish in your fetch function.

Comments