Tkinter Message Widget: Displaying In-App Text


Tkinter Message widget

The Tkinter Message widget is designed to display multiline text directly within the application's interface, providing an embedded, non-intrusive way of showing information.
import tkinter as tk
my_w = tk.Tk() # Parent window 
my_w.geometry("620x300")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
font1=['Arial',52,'normal'] # Higher size font 

msg1=tk.Message(my_w,text='Welcome to plus2net tkinter section',
                font=font1,bg='lightgreen',aspect=200)
msg1.grid(row=1,column=1,padx=40,pady=15) 

my_w.mainloop()  # Keep the window open

Using the Tkinter Message Widget for Dynamic Help Messages 🔝


Dynamic In-Process Messages in Tkinter: Implementing Message Widget

The Message widget in Tkinter displays dynamic help messages that update the text as the user navigates through different input fields.

The widget maintains a fixed size; it automatically adjusts the text line breaks to fit varying message lengths.

This functionality is controlled by event handlers linked to the input widgets, ensuring the displayed text updates appropriately.

Input Help Message box

import tkinter as tk
my_w = tk.Tk() # Parent window 
my_w.geometry("600x300")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
font1=['Arial',22,'normal'] # Higher size font 
font2=['Arial',18,'normal'] # Higher size font 
my_w.columnconfigure(4,weight=1) # to fix size of Message box

def my_food(*args):
    if my_var.get()==2:
        my_str.set('We have excellent Veg items')
    else:
        my_str.set('Our Chicken Pizza is the best ')

lb1=tk.Label(my_w,text='Name',font=font2)
lb1.grid(row=1,column=1,padx=20,pady=40)
e1=tk.Entry(my_w,bg='yellow',font=font2,width=10,)
e1.grid(row=1,column=2,columnspan=2,padx=2,sticky='w')

lb1=tk.Label(my_w,text='Food',font=font2)
lb1.grid(row=2,column=1,padx=2,pady=10)

my_var = tk.IntVar() # for Radiobutton
r1=tk.Radiobutton(my_w,variable=my_var,bg='red',text='Non Veg',
        font=font1,selectcolor='lightblue',indicatoron=0,value=1)
r1.grid(row=2,column=2,padx=2)
r2=tk.Radiobutton(my_w,variable=my_var,bg='red',text='Veg',
        font=font1,selectcolor='lightblue',indicatoron=0,value=2)
r2.grid(row=2,column=3,padx=2)

bt1=tk.Button(my_w,text='Order',font=font2,bg='lightpink',
              command=lambda:my_str.set('Thanks, data stored'))
bt1.grid(row=3,column=2,padx=2,pady=20)

my_str=tk.StringVar(value='Message here') # for Message widget 
msg1=tk.Message(my_w,textvariable=my_str,
                font=font1,bg='lightgreen',width=200,aspect=250)
msg1.grid(row=1,column=4,padx=10,pady=40,rowspan=3,sticky='nsew')

my_var.trace_add('write',my_food) # Radiobutton Click event 
e1.bind('<FocusIn>',lambda n:my_str.set('Your Name')) # Entry box 
e1.bind('<FocusOut>',lambda n:my_str.set('Welcome'))

my_w.mainloop()  # Keep the window open

Attributes of Message widget 🔝

Listing all attributes with values ( What is config() ? )
for options  in msg1.config():
    print(options,':',msg1[options])
Attribute Description
anchor Determines where the text is positioned within the widget if the widget has more space than required for the text. Default is center.
aspect Controls the ratio of width to height of the widget when resizing. Default value is 150
bg or background Sets the background color of the widget.
bd or borderwidth Width of the border around the widget. Default value is 1 pixels. Use this along with relief to get visible border around the Message widget.
cursor The cursor that appears when the mouse is over the message widget. Examples include arrow, circle, dotbox, etc.
font The font used for the message text, specified as a tuple (e.g., ('Helvetica', 12, 'bold')).
fg or foreground Color of the text on message widget.
highlightbackground Color of the focus highlight when the widget does not have focus.
highlightcolor Color of the focus highlight when the widget has focus.
highlightthickness Thickness of the focus highlight. Default : 0
justify Controls how the text is justified: LEFT, CENTER, or RIGHT. Default : LEFT
padx Horizontal padding of the text within the widget.
pady Vertical padding of the text within the widget.
relief Type of the border around the widget. Options are FLAT, RAISED, SUNKEN, GROOVE, and RIDGE.
Use this along with borderwidth ( bd ) to get visible border around the Message widget.
text The text displayed by the widget, which can include plain text or properly formatted text.
takefocus Should be included in the keyboard focus traversal or not ( True , False), Default : 0
textvariable A variable (e.g., a Tkinter StringVar) used to manage the widget’s text dynamically, instead of using the text attribute. ( my_str in above example )
width Width of the widget. Set explicitly or determined by content; affects text wrapping if specified.

Updating background color on focus based on takefocus attribute

takefocus attribute to update background color
the Message widget changes its background color to light green when it gains focus (using the Tab key) and switches back to white when it loses focus. The takefocus=True attribute allows the Message widget to be focusable during keyboard navigation. The Entry widget next to it also participates in the Tab focus order.
import tkinter as tk

def on_focus_in(event):
    msg.config(bg='lightgreen')

def on_focus_out(event):
    msg.config(bg='white')

my_w = tk.Tk()
my_w.geometry("400x300")

msg = tk.Message(my_w, text="Keep on pressing Tab.", width=300, font=("Arial", 14), takefocus=True)
msg.grid(row=0, column=0, padx=10, pady=10)

l1=tk.Entry(my_w,width=20)
l1.grid(row=0,column=1)
# Binding focus in and out events
msg.bind("<FocusIn>", on_focus_in)
msg.bind("<FocusOut>", on_focus_out)

my_w.mainloop()

Text wrapping in message widget 🔝

Text wrapping in the Message widget is primarily managed through two attributes:

width: This attribute sets the width of the widget in pixels. If the text is longer than the width provided, it will automatically wrap to the next line. Unlike the Label widget, where you need to manually insert newline characters to wrap text, the Message widget handles this automatically based on the width we set.

aspect: This attribute controls the width-to-height ratio of the text. The aspect attribute is a percentage that determines the ratio of line length to font size. A higher value increases the width of each line relative to the height. It adjusts how tightly or loosely the text fits within the given width.

Differences Between Message and Label Widgets in Tkinter 🔝

Feature Label Message
Text Wrapping The Label widget does not automatically wrap text. Newline characters (\n) must be manually inserted for multiline text. The Message widget automatically wraps text based on the widget's width, controlled by the width attribute.
Use Case Best suited for displaying a small amount of text, such as titles, labels for inputs, or brief instructions. Designed for longer text that requires wrapping, making it ideal for variable-length text in the GUI.
Configuration Options Offers basic text display options like font customization, background and foreground colors, and alignment. Provides similar font and color settings as Label, plus detailed control over text wrapping through the aspect attribute.
Performance Faster and more efficient for handling static text that doesn’t change frequently or require wrapping. Flexible with dynamic text and wrapping, but may be slightly less efficient due to more complex text handling capabilities.

Preventing resizing of message widget 🔝

Depending on the amount of text we are displaying ( dynamically ) the width and height of the message widget will change. To keep it fixed in different layouts we have to use different filling methods based on the layout we use.
pack(fill=BOTH)
grid : Use the rowconfigure or columnconfigure
my_w.columnconfigure(4,weight=1)
Use the sticky option with row and column.
msg1.grid(row=1,column=4,padx=3,rowspan=3,sticky='nsew')

Key Difference Between Message Widget and MessageBox in Tkinter 🔝

The main difference between the Message widget and the MessageBox in Tkinter lies in their intended use and functionality:

Message Widget: The Message widget is used within a Tkinter application window to display text. It is similar to a Label widget but is specifically designed to handle multiline text with automatic line wrapping based on the widget's width. It is ideal for displaying dynamic information within the main application interface.

Messagebox: The MessageBox, on the other hand, is used to pop up a separate window that displays a message to the user. It is typically used for alerts, warnings, and asking the user to make decisions (like Yes/No or OK/Cancel). MessageBoxes interrupt the flow of application use until the user responds, unlike the Message widget, which is just part of the regular application interface.

Handling Scrollbars with Tkinter Message Widget

The Tkinter Message widget does not natively support scrollbars because it is designed primarily for displaying simple, static text that fits within the allocated space. Unlike the Text widget, which is intended for handling longer, scrollable text inputs, the Message widget lacks the internal mechanisms necessary for scrollbar integration, It is missing the commands yview and xview that are used for the scrolling protocol for tracking the visible portion of content or interacting with a scrollbar widget.

To implement scrollable text in a Tkinter application where the content exceeds the visible area, it is recommended to use the Text widget instead.

Events

takefocus attribute to update background color
While the Message widget in Tkinter doesn't directly support events like focus or mouseovers, you can simulate such behaviors by binding the Message widget to specific events like (for mouseover) or (for mouse leave). Below is an example where the background color of the Message widget changes when the mouse hovers over it:
import tkinter as tk

def on_enter(event):
    msg.config(bg='lightblue')

def on_leave(event):
    msg.config(bg='yellow')

my_w = tk.Tk()
my_w.geometry("400x200")

msg = tk.Message(my_w, text="Hover over this message!", width=300, font=("Arial", 14))
msg.grid(row=0, column=0, padx=10, pady=50)

# Binding mouseover and mouse leave events
msg.bind("<Enter>", on_enter)
msg.bind("<Leave>", on_leave)

my_w.mainloop()

Questions 🔝


Understanding Tkinter Message Widget - Python GUI Tutorial #message #tkinter #pythongui #helpMessage


Messagebox simpledialog to take user inputs
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer