在TKinter弹出窗口中打印带换行符的列表

2024-04-26 00:14:54 发布

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

我有一张单子:

runner.sublist = [["one","two","three"],["red","black","blue]]

这个类的定义

class popupWindow(object):
    def __init__(self, master, txt):
        top = self.top = Toplevel(master)
        self.l = Label(top, text=txt)
        self.l.pack()
        self.b = Button(top, text='Fine....', command=self.cleanup)
        self.b.pack()

def popup(self,txt):
    self.w=popupWindow(self.master, txt)
    self.master.wait_window(self.w.top)

我试着用这个按钮来创建一个弹出窗口,在弹出窗口中打印runner.sublist列表,在每组元素后面加上换行符(第一行是一二三,第二行是红黑蓝,等等)

def print_it(op):
    out = '\n'.join(op)
    return out


class mainWindow(object):
    def __init__(self,master):
        self.master=master
        self.b2=Button(master,text="print value",command=lambda: self.popup(print_it(runner.sublist)))
        self.b2.pack()

但是,此代码返回以下错误:

TypeError: sequence item 0: expected string, list found

很明显,我在传递一个列表,其中我应该有一个字符串,但我完全不明白为什么它会得到一个列表!我尝试在不同的地方将一些值强制转换成字符串,但没有成功。你知道吗

有什么想法吗?谢谢!你知道吗


Tags: textselfmastertxt列表objectinittop
1条回答
网友
1楼 · 发布于 2024-04-26 00:14:54

join可以加入list of strings,但不能加入list of lists of strings。你知道吗

(见:lambda: self.popup(print_it(runner.sublist))

'\n'.join( [["one","two","three"],["red","black","blue"]] ) # error

你必须改变。例如:

def print_it(op):
    return '\n'.join( ' '.join(line) for line in op )

得到两条线

one two three
red black blue

相关问题 更多 >

    热门问题