简体   繁体   English

如何为Tkinter输入分配变量?

[英]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. 例如,如果用户输入'A''1''X'那么我需要将文件A1X从网络驱动器复制到本地驱动器。

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() 您需要使用StringVar()并为Entry()提供一个textvariable

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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