从具有多个参数列表的多个对象列表调用方法

2024-04-27 16:42:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

现在,我想应用插入函数。从另一个函数kg_到\u磅\u盎司\u g,我得到了文本小部件的值列表:

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

如何将insert应用于输出,以便pound进入TextWidget1,盎司进入TextWidget2,gram进入TextWidget3,并在一行表达式中只调用函数kg_to_pounds_ounces_grams一次? 德尔特也一样-也适用于一条生产线?在

编辑: 我试着用三条线来完成这两件事:

^{pr2}$

但它仍然困扰着我——难道没有优雅的双线解决方案吗?在

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

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

Tags: totextoutputdefcolumnwindowgridrow
1条回答
网友
1楼 · 发布于 2024-04-27 16:42:33

与您的delete行类似,您可以在一行中执行插入。。。但出于可读性的考虑,我不推荐这些单行程序。在

需要注意的是,将lambda与map结合使用有点傻,列表理解会更清晰:

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

插入部分:

^{pr2}$

我想你甚至可以把它们结合起来,但我还是不推荐这两种。在

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

相关问题 更多 >