【问题标题】:how to return a function value that is in a dictionary如何返回字典中的函数值
【发布时间】:2019-02-26 20:07:55
【问题描述】:

我有一个 tkinter 项目,它尝试在单击按钮后创建未知数量的条目并获取它们的值!我尝试了很多方法,但声明后我无法返回Entry值!这是我的方法:

from tkinter import Entry, Tk, Button

l = [50]


def entry(x, y):
    global data
    e = Entry()
    e.place(x=x, y=y, height=20, width=100)
    data = e.get()
    return data


def loop():
    n = 0
    s = l[0]
    for_x = 10
    for_y = 10
    global en
    en = dict()
    while True:
        if n == s:
            break
        else:
            en[n] = entry(for_x, for_y)
            n = n + 1
            if for_y >= 400:
                for_x = for_x + 110
                for_y = 10
                print("110")
            else:
                for_y = for_y + 30
                print("30")
            print("finally")


root = Tk()

root.minsize(500, 500)

loop()


def dp():
    print(en)


b = Button(command=dp)
b.place(x=480, y=400)
root.mainloop()

然而,字典确实显示了值,但只显示了小部件声明时的值!我想在声明后得到它的价值!有什么想法吗?

【问题讨论】:

  • 你再也不会引用全局data;为什么要创建它? entry 可以只返回 e.get(),然后将该值分配给 en[n]
  • 同样,不清楚为什么l 是一个全局变量,而不是loop 将列表(或该列表中的唯一元素)作为参数。
  • 最后,en 只是Entry 对象在它们首次创建时所持有的值数组。您需要自己存储Entry 对象,并在单击按钮时调用每个对象的get 方法。
  • 这是我的问题!我不知道第二次,如何存储Entry对象!我也在为未知数制作代码,L 用于测试!我知道它需要大量清洁,但它只是为了解决问题!
  • entry 应该只返回e,而不是e.get()

标签: python python-3.x loops dictionary tkinter


【解决方案1】:

在创建输入框期间您正在运行e.get。您需要运行e.get() 与其他事件相关联。您还应该返回 Entry 对象而不是返回数据,例如:

def entry(x, y):
    e = Entry()
    e.place(x=x, y=y, height=20, width=100)
    return e

def loop():
    n = 0
    s = l[0]
    for_x = 10
    for_y = 10

    global entry_list

    entry_list = []  # Used to store all of the entry widgets you make

    while True:
        if n == s:
            break
        else:
            entry_list.append(entry(for_x, for_y)) # Adds a new entry widget to the list
            n = n + 1
            if for_y >= 400:
                for_x = for_x + 110
                for_y = 10
                print("110")
            else:
                for_y = for_y + 30
                print("30")
            print("finally")

def dp():
    # Get the value of each entry box
    en = []
    for e in entry_list:
        en.append(e.get())
    print(en)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多