【问题标题】:Call method from list of multiple objects with list of multiple arguments从具有多个参数列表的多个对象列表中调用方法
【发布时间】:2018-07-05 15:49:27
【问题描述】:

我在 Python 中使用 Tkinter,并创建了多个 TextWidget。 我将这些对象放在一个名为 output 的列表中。 每个文本部件都有 text 属性,可以通过 .delete(index1,index2) 和 insert(index, chars) 方法更改。

现在,我想应用 insert 函数。从另一个函数 kg_to_pounds_ounces_grams 我得到一个文本小部件的值列表:

def kg_to_pounds_ounces_grams(kilogram):
    pound = kilogram * 2.20462
    oounce = kilogram * 35.274
    gram = kilogram * 1000
    return [pound, oounce, gram]

如何将插入应用到输出,以便磅进入 TextWidget1,盎司进入 TextWidget2,克进入 TextWidget3,并在一行表达式中只调用一次函数 kg_to_pounds_ounces_grams? delte 也是如此 - 也适用于一行?

编辑: 我设法在三行中做到了这两点:

for textWidget,weight  in zip(output, kg_to_pounds_ounces_grams(kg) ):
    textWidget.delete(1.0, END)
    textWidget.insert(END,weight)

但它仍然困扰着我 - 没有优雅的两行解决方案吗?

为了更好的理解,我把完整的代码放在这里:

from tkinter import *

window = Tk()


def kg_to_pounds_ounces_grams(kilogram):
    pound = kilogram * 2.20462
    ounce = kilogram * 35.274
    gram = kilogram * 1000
    return [pound, ounce, gram]


def convert_button_pressed():
    try:
        kg = float(e1_text.get())
    except:
        kg = float("NaN")
    map(lambda x: x.delete(1.0, END), output)
    # Missing Code goes here!


l1 = Label(window, text="Kg")
l1.grid(row=0, column=0)

e1_text = StringVar()
e1 = Entry(window, textvariable=e1_text)
e1.grid(row=0, column=1)

b1 = Button(window, text="Convert", command=convert_button_pressed)
b1.grid(row=0, column=2)

t1 = Text(window, height=1, width=20)
t1.grid(row=1, column=0)

t2 = Text(window, height=1, width=20)
t2.grid(row=1, column=1)

t3 = Text(window, height=1, width=20)
t3.grid(row=1, column=2)

output = [t1, t2, t3]

window.mainloop()

【问题讨论】:

  • 我敢肯定,以正确的方式使用 map、lambda 和 for 是可能的。我的最后一次(失败)尝试如下所示:map(lambda x: x.insert(END,out) for out in kg_to_pounds_ounces_grams(kg), output)
  • 为什么拥有两行解决方案很重要?试图压缩代码只会使其更难阅读和更难调试。
  • 你只是想插入函数返回的三个值吗?简单地将结果加入字符串并插入字符串有什么问题?

标签: python dictionary tkinter lambda functional-programming


【解决方案1】:

与您的 delete 行类似,您可以在一行中进行插入...但为了便于阅读,我不推荐这些单行。

需要注意的是,将 lambda 与 map 结合使用有点傻,列表推导会更简洁:

[x.delete(1.0, END) for xin output]

对于插入:

[x.insert(END, w) for x, w in zip(output, kg_to_pound_ounces_grams(kg))]

我想你甚至可以将它们结合起来,但我再次不推荐其中任何一个。

[(x.delete(1.0, END), x.insert(END, w)) for x, w in zip(output, kg_to_pound_ounces_grams(kg))]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-17
    • 2018-05-01
    • 2019-02-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多