Search code examples
python-3.xtkinterwidgetmessagepack

Message widget not filling frame using tkinter


I'm creating a simple user dialog window with a basic text on top and a tree view with one column below, that gives the user a couple of choices. A button at the bottom is used to confirm the selection.

Now I can't get the Message widget, which I use to display the instructions, to fill the Frame I've created for it. Meanwhile, the Treeview widget fills the Frame as I want it to.

Many proposed solutions on other StackOverflow questions state, that putting my_message.pack(fill=tk.X, expand=True) should work. It doesn't in my case.. In a different scenario it is recommended to put my_frame.columnconfigure(0, weight=1), which doesn't help either.

Here is the code:

import tkinter as tk
from tkinter import ttk

class MessageBox(object):
    """ Adjusted code from StackOverflow #10057662. """

    def __init__(self, msg, option_list):

        root = self.root = tk.Tk()
        root.geometry("400x400")
        root.title('Message')
        self.msg = str(msg)
        frm_1 = tk.Frame(root)
        frm_1.pack(expand=True, fill=tk.X, ipadx=2, ipady=2)
        message = tk.Message(frm_1, text=self.msg)
        message.pack(expand=True, fill=tk.X) # <------------------------------------ This doesn't show the desired effect!
        frm_1.columnconfigure(0, weight=1)

        self.tree_view = ttk.Treeview(frm_1)
        self.tree_view.heading("#0", text="Filename", anchor=tk.CENTER)
        for idx, option in enumerate(option_list):
            self.tree_view.insert("", idx+1, text=option)
        self.tree_view.pack(fill=tk.X, padx=2, pady=2)



choice_msg = "Long Test string to show, that my frame is unfortunately not correctly filled from side to side, as I would want it to."
choices = ["Test 1", "Test 2", "Test 3"]
test = MessageBox(choice_msg, choices)
test.root.mainloop()

I'm slowly going nuts, because I know that there is probably something very basic overruling the correct positioning of the widget, but I've been trying different StackOverflow solutions and browsing documentation for hours now with no luck.


Solution

  • Try to set a width of message in the tk.Message constructor, something like this:

        message = tk.Message(frm_1, text=self.msg, width=400-10)  # 400 - is your window width
        message.pack()  # In that case you can delete <expand=True, fill=tk.X>