Wouter Wouter - 1 year ago 87
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


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)

variables = []
for field in fields:
lab1= Label()
lab = Label(left, text=field)
ent = Entry(rite)
var = StringVar()
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)))

Any suggestions?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download