如何在Tkinter的AutoScroll List Box中实现文本自动换行?
Got it, let's sort out this text wrapping issue in your AutoScroll List Box right away. The wrap=WORD parameter you're thinking of is exactly what you need—you just have to add it when initializing your Listbox component.
Here's how to adjust your code:
In the __init__ method where you create the Listbox instance, add wrap=WORD to the list of arguments:
self.listbox_log = Listbox( frame, bg="black", height=12, fg="cyan", font=('Times', 45), wrap=WORD)
If you prefer to set it after initialization (though adding it during setup is cleaner), you can also use the configure method later:
self.listbox_log.configure(wrap=WORD)
Why this works:
The wrap=WORD option tells the Listbox to break text at word boundaries instead of cutting off mid-word when the content exceeds the widget's width. Since you're already using fill=X when packing the Listbox, it will expand to fit the width of its parent frame, so wrapped text should display properly across multiple lines for each list item.
Quick improvement note:
I noticed your scrollbar was only packed with side=RIGHT—adding fill=Y will make it stretch to match the full height of the Listbox, which looks better and works more intuitively for scrolling through wrapped content.
Here's the updated full __init__ method for clarity:
def __init__(self, master): frame = Frame(master) frame.pack(fill=X, padx=10, pady=1) instructions() # Added wrap=WORD here to enable text wrapping self.listbox_log = Listbox( frame, bg="black", height=12, fg="cyan", font=('Times', 45), wrap=WORD) self.scrollbar_log = Scrollbar(frame) # Added fill=Y to make scrollbar match Listbox height self.scrollbar_log.pack(side=RIGHT, fill=Y) self.listbox_log.pack(fill=X) self.listbox_log.configure(yscrollcommand=self.scrollbar_log.set) self.scrollbar_log.configure(command=self.listbox_log.yview) # Just to show unique items in the list self.item_num = 0
内容的提问来源于stack exchange,提问作者Eissa Faheem

