繁体   English   中英

如何使用 TkInter 中的 label 打印元组列表?

[英]How to print a list of tuples using a label in TkInter?

我正在使用 Python 和 TkInter 制作配方处理程序。 我有一个包含元组=>(成分,数量)的列表。 我需要使用 label 将其放置到屏幕上。 我想消除引号和列表括号,即[]但我想保留元组括号,即()

mylist = [('a','2'),('b','4')]

我已经尝试遍历列表,但它只是将项目放在另一个之上,并没有显示所有内容。

预计 Output

Ingredients: (a,2), (b,4)

尝试:

', '.join(f"({', '.join(str(x) for x in item)})" for item in mylist)

下面的代码确实去掉了 a 和 b 中的''

from tkinter import *

root = Tk()

myList = [('a',2),('b',4)]

for index,item in enumerate(myList):
    Label(root,text=f'Ingredients: {item}').pack(pady=index+10)

root.mainloop()

但是在这个例子中,我让它在没有''情况下被分开,但这里的元组不再是一个元组,而是一个看起来像一个元组的普通文本。 试试这个(@acw1668 的回答给了我一个提示)

from tkinter import *

root = Tk()

myList = [('a', '2'), ('b', '4')] #your initial list
final = [] #making an empty list to populate later on

new = (', '.join(f"({', '.join(str(x) for x in item)})" for item in myList)) # removing the quote and creating a single word

item1 = new[0:6] #splitting into two tuples by slicing
item2 = new[8:14] #doing the same with second item

final.append(item1) #appending it to the final list
final.append(item2) #doing the same 

for index,item in enumerate(final): #looping through the list giving each item in the list a number
    Label(root,text=f'Ingredients: {item}').pack(pady=index+10) #placing it on the screen with label and packing with padx

root.mainloop()

希望对您有所帮助,如果还有更多错误,请告诉我:D

干杯

这需要一个自定义的toString方法。 它可能是这样的:

def toString(arg):
    string = "Ingredients: "
    for part in arg:
        string += str(part) + ", "
    return string

暂无
暂无

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

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