PySimpleGui中能否为sg.Output组件的每行内容设置不同字体样式?
Hey there! Great question—unfortunately, the sg.Output element you’re using right now is just a wrapper around Python’s standard print() function, which doesn’t support styling individual lines with color or bold text directly. But don’t worry, there’s a straightforward fix by switching to a sg.Multiline element instead. It’s built on Tkinter’s Text widget, which lets you add formatted text using custom "tags" for styles like bold, color, and more.
Here’s how to modify your code to get the behavior you want:
Step 1: Replace sg.Output with sg.Multiline
First, update your chat window layout to use a read-only Multiline element for displaying messages. This gives you full control over styling:
chatWindow = [ # Read-only Multiline for chat history (auto-scrolls to new messages) [sg.Multiline(size=(90, 37), font=('Helvetica 10'), key='-CHAT-', readonly=True, autoscroll=True)], # Input area and buttons (kept mostly the same) [sg.Multiline(size=(75, 5), enter_submits=False, key='-QUERY-', do_not_clear=False), sg.Button('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0]), bind_return_key=True), sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))] ]
Step 2: Create a Helper Function for Styled Messages
Make a reusable function to add messages with different styles. We’ll define two tags: one for your bold, colored messages, and another for other users’ distinct styling:
def add_styled_message(window, message, is_self=False): chat_box = window['-CHAT-'] # Define custom styles using Tkinter tags if is_self: # Bold blue for your messages chat_box.tag_configure('self_msg', font=('Helvetica', 10, 'bold'), foreground='#0066cc') chat_box.write(f"You: {message}\n", tag='self_msg') else: # Gray text for other users' messages (adjust color to your preference) chat_box.tag_configure('other_msg', font=('Helvetica', 10), foreground='#666666') chat_box.write(f"Friend: {message}\n", tag='other_msg')
Step 3: Update the Event Loop to Use the Helper
Modify your main event loop to send messages through the styled function instead of print():
window = sg.Window('Simple Chat App', chatWindow) while True: event, values = window.read() if event == sg.WIN_CLOSED or event == 'EXIT': break if event == 'SEND': user_input = values['-QUERY-'].strip() if user_input: # Add your message with bold style add_styled_message(window, user_input, is_self=True) # Simulate a reply from another user (replace with real chat logic!) add_styled_message(window, f"Got your message: {user_input}", is_self=False) # Clear the input field after sending window['-QUERY-'].update('') window.close()
Extra Customization Tips
- Multiple Users: Add more tags (e.g.,
user_alice,user_bob) with unique colors or backgrounds to distinguish between different participants. Use thebackgroundparameter intag_configurefor colored message bubbles. - Font Variations: Adjust the
fontparameter to use different sizes, fonts, or styles like italic ('italic') or underline ('underline'). - Timestamps: Include timestamps by adding
datetime.datetime.now().strftime("%H:%M")to your message strings.
This approach gives you full control over message styling, making it easy to tell apart your messages from others in the chat.
内容的提问来源于stack exchange,提问作者Mark McGookin

