简体   繁体   中英

How do I assign a variable to a Tkinter input?

I am using the following code to create a widget with three inputs.

I am able to modify this code to format the widget how I want, but I then need to copy files based on the input from the fields in the widget. For example, if the user inputs 'A' , '1' , and 'X' then I need to copy file A1X from a network drive to the local drive.

I think I need to assign each input field to a variable and then I can set up a conditional to get the correct file, but I cannot figure out how to set up these variables.

from tkinter import *
fields = 'Project #', 'Reel #', 'Batch #'

def fetch(entries):
   for entry in entries:
   field = entry[0]
   text  = entry[1].get()
   print('%s: "%s"' % (field, text)) 

def makeform(root, fields):
   entries = []
   for field in fields:
      row = Frame(root)
      lab = Label(row, width=15, text=field, anchor='w')
      ent = Entry(row)
      row.pack(side=TOP, fill=X, padx=5, pady=5)
      lab.pack(side=LEFT)
      ent.pack(side=RIGHT, expand=YES, fill=X)
      entries.append((field, ent))
   return entries

if __name__ == '__main__':
   root = Tk()
   ents = makeform(root, fields)
   root.bind('<Return>', (lambda event, e=ents: fetch(e)))   
   b1 = Button(root, text='OK',
      command=(lambda e=ents: fetch(e)))
   b1.pack(side=RIGHT, padx=5, pady=5)
   b2 = Button(root, text='Reset', command=root.quit)
   b2.pack(side=RIGHT, padx=5, pady=5)
   root.mainloop()
  1. You should use a dictionary for entries.
  2. Your function fetch is on the correct path.

Here is a fixed version(assuming entries is a dictionary):

def fetch(entries):
   filename = ''.join(entries[f].get() for f in fields)
   print(filename)
   #whatever you want to do with the result

You need to use a StringVar() and provide a textvariable to Entry()

for field in fields:
    row = Frame(root)
    lab = Label(row, width=15, text=field, anchor='w')
    entry_variable = StringVar(root)
    ent = Entry(row, textvariable=entry_variable)
    row.pack(side=TOP, fill=X, padx=5, pady=5)
    lab.pack(side=LEFT)
    ent.pack(side=RIGHT, expand=YES, fill=X)
    entries.append((field, entry_variable))

Get the data (after fixing indentation):

def fetch(entries):
    for entry in entries:
        field = entry[0]
        text  = entry[1].get()
        print('%s: "%s"' % (field, text)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM