简体   繁体   English

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

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

I'm making a recipe handling program using Python and TkInter.我正在使用 Python 和 TkInter 制作配方处理程序。 I have a list that contains tuples => (Ingredient, Quantity).我有一个包含元组=>(成分,数量)的列表。 I need to use a label to place it onto the screen.我需要使用 label 将其放置到屏幕上。 I want to eliminate the quotes and the list brackets ie [] but I want to keep the tuple brackets ie ()我想消除引号和列表括号,即[]但我想保留元组括号,即()

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

I have tried iterating through the list but it just places the items one on top of the other and doesn't show everything.我已经尝试遍历列表,但它只是将项目放在另一个之上,并没有显示所有内容。

Expected Output预计 Output

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

Try:尝试:

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

The below code does get rid of the '' in a and b:下面的代码确实去掉了 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()

But in this example i got it to be separated without the '' but here the tuple no longer is a tuple but instead just a normal text that looks like a tuple.但是在这个例子中,我让它在没有''情况下被分开,但这里的元组不再是一个元组,而是一个看起来像一个元组的普通文本。 Give this a try (Answer by @acw1668 gave me a hint on this)试试这个(@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()

Hope it helped, let me know if any more errors:D希望对您有所帮助,如果还有更多错误,请告诉我:D

Cheers干杯

This requires a custom toString method.这需要一个自定义的toString方法。 It could be something like this:它可能是这样的:

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