我想在 Text Widget 中列出 frame.conifg 的串列。應從文本中洗掉字符“{}”。有人可以向我解釋一下,為什么不會用以下代碼洗掉?
liste = frame_01.config()
for item in liste:
texteditor.insert(tk.INSERT, (item.strip("{}"), ":", liste[item], "\n"))
這是串列的樣子: 在此處輸入影像描述
使用此代碼,我收到以下錯誤訊息: texteditor.insert(tk.INSERT, (item.translate(str.maketrans('', '', '{}')), ":", self.mainwindow.liste[ item], "\n")) 型別錯誤:串列索引必須是整數或切片,而不是 str
for item in liste:
texteditor.insert(tk.INSERT, (item.translate(str.maketrans('', '', '{}')), ":", liste[item], "\n"))
uj5u.com熱心網友回復:
花括號不在資料中,它們僅由 tkinter 添加,因為您將串列傳遞給需要字串的函式。Tcl(tkinter 使用的嵌入式語言)通過在具有空格或制表符的串列元素周圍添加大括號來對串列進行與 Python 不同的編碼。
解決方案是明確格式化資料,而不是試圖讓 Tcl 格式化資料。一種方法是這樣做:
for item in liste:
# convert the list of values to a list of strings
values = [str(x) for x in liste[item]]
# explicitly join the list of strings to create a single string
str_values = " ".join(values)
# insert the string into the text widget
textedit.insert("end", f"{item}: {str_values}\n")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/385734.html
