将值设置为for循环中的tkinter Entry小部件时出现问题

时间:2017-06-15 05:27:04

标签: python python-3.x tkinter

我尝试使用for循环设计具有5个条目小部件(两侧)范围的小tkinter窗口,就像下面的图像一样。

enter image description here

现在我的要求是在左侧窗口小部件中键入一些值,它应该在给出 Tab 键的同时自动显示在右侧。我尝试使用lambda的bind方法并获得了值。但我想知道如何在每个小部件上设置值。

我的代码

import tkinter as tk
root = tk.Tk()
num = 5

def my_funct(var):
    e.set(var)

r=0
for y in range(num):
    e = tk.StringVar()

    y = tk.Entry(root)
    y.bind("<Tab>", lambda event, y=y:my_funct(y.get()))
    y.grid(row=r, column=1)

    z = tk.Entry(root, textvariable=e)
    z.grid(row=r, column=2)
    r +=1

root.mainloop()

我得到的结果如下图所示。有人能用我的代码帮助我实现我的期望吗?

enter image description here

正如您所知,该值仅显示在每个Tab键的最后一个窗口小部件中。有人可以帮助我解决这个问题,请解释我如何实现我所需的输出。

提前致谢!

1 个答案:

答案 0 :(得分:1)

您的问题源于您每次都重新分配StringVar这一事实,因此e始终是最后创建的{entry:variable}。您需要一个结构来保存这些内容,例如dict import tkinter as tk root = tk.Tk() num = 5 pairs = {} def my_funct(entry): var = pairs.get(entry) if var is not None: var.set(entry.get()) # r = 0 for _ in range(num): e = tk.StringVar() y = tk.Entry(root) y.bind("<Tab>", lambda event, y=y:my_funct(y)) y.grid(row=_, column=1) z = tk.Entry(root, textvariable=e) z.grid(row=_, column=2) # r +=1 pairs.update({y:e}) root.mainloop() 对。

这是一个片段:

              SELECT TOP 1 [ID]
              FROM [forecast].[dbo].[forecast_tool_product_identifiers]
              CROSS APPLY (
                 SELECT [COL1], 
                        -- ... 
                        [COL12]
                 FROM [forecast].[dbo].[forecast_tool_rule_templates]
                 WHERE [template_name] = 'testADI001' -- Current rule Template
                    AND [rule_sequence] = '1') tpl
              WHERE [macro_products_id] = '3' -- Macro Prouduct Dropdown
              AND ISNULL([source_attribute_1],' ') LIKE  tpl.[COL1]
               -- ...   
              AND ISNULL([source_attribute_12],' ') LIKE  tpl.[COL12] 
              AND [ID] -- Application Drop Down values below
       IN 
      (SELECT [ID]
      FROM [forecast].[dbo].[forecast_tool_product_identifiers]
      WHERE [macro_products_id] = '3' AND
      ISNULL([source_attribute_1],' ') LIKE '%' AND
      ISNULL([source_attribute_2],' ') LIKE '%' AND
      ISNULL([source_attribute_3],' ') LIKE '%' AND
      ISNULL([source_attribute_4],' ') LIKE '%' AND
      ISNULL([source_attribute_5],' ') LIKE '%' AND --  ETH-10GE (TEST VALUE)
      ISNULL([source_attribute_6],' ') LIKE '%' AND
      ISNULL([source_attribute_7],' ') LIKE 'BLTMMDCH' AND --  NYCMNY54 (TEST VALUE)
      ISNULL([source_attribute_8],' ') LIKE '%' AND
      ISNULL([source_attribute_9],' ') LIKE '%' AND --  AGSTMEST (TEST VALUE)
      ISNULL([source_attribute_10],' ') LIKE '%' AND
      ISNULL([source_attribute_11],' ') LIKE '%' AND
      ISNULL([source_attribute_12],' ') LIKE '%');--  KT (TEST VALUE)