首页 > 解决方案 > Python Tkinter中列表和字典的文本换行

问题描述

我创建了一个程序,用于使用 Python Tkinter 找出一组数字的所有可能组合。但是当输出发送到 GUI 时。输出布局非常混乱(见图)。

我的程序的输出

我用过wrap = 195output_text.configure但它没有很好地整理输出。另外,我尝试使用warp = "WORD"并发出此错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:\Eclipse IDE\Workspace\OCR A-LEVEL Programming Challenges\PIN Code Sequencer.py", line 15, in btn1_clicked
    output_text.configure(text = "Output: " + str(output1), wrap="WORD")
  File "C:\Python\lib\tkinter\__init__.py", line 1637, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Python\lib\tkinter\__init__.py", line 1627, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: bad screen distance "WORD"

我希望程序在一行上显示 2-3 个组合。

这是我的代码:

from tkinter import *
from itertools import *

window =Tk()
window.geometry("480x270")
window.title("PIN Code Combinations")

title1 = Label(window, text = "Input Numbers To Find Out All the Possible Combination!")
title1.grid(row = 0, column = 0)

input1 = Entry(window, width = 20)
input1.grid(row = 1, column = 0)

output_text = Label(window, text = "Output: ")
output_text.grid(row = 3, column = 0)

def btn1_clicked():
    temp = input1.get()
    output1 = list(permutations(temp))
    output_text.configure(text = "Output: " + str(output1), wrap=195)

btn1 = Button(window, text = "Calculate Combinations", command=btn1_clicked )
btn1.grid(row = 1, column = 1)

window.mainloop()

Python 3.8 版

标签: pythontkinter

解决方案


最简单的解决方案是使用 python 的pprint模块为您格式化数据。或者,您可以编写自己的函数来进行格式化。Tkinter 本身不支持格式化数据。

例如,

import pprint
...
text = pprint.pformat(output1, indent=4)
output_text.configure(text = "Output: " + text, wrap=195)

推荐阅读