Search code examples
pythonimagetkintertextwidget

How to center an image in the tkinter Text widget?


A button on the main application opens a help file that is a text file imported from the file system. Before the text I want to display an image. This code places the image properly before the text BUT I can't center it. Here's the code:

I'm unsure of the correct hierarchy. I have first root, then TopLevel followed by Frame with scroll bar and then Text widget. The image is in the Text widget and the Text widget is in the Frame. All of the scrolling works well but I can't get the image (img) to center within the Text widget.

def txt_wig(self):
    global img
    img = PhotoImage(file='spreadsheet.gif')
    toplvl = Toplevel(root,padx=20,pady=20)
    toplvl.geometry('700x600')
    toplvl.configure(border = 10, relief = 'sunken', padx=10, pady=10)
    frame1 = Frame(toplvl,pady=10)
    frame1.pack()
    text_scroll = Scrollbar(frame1, orient="vertical")
    text_scroll.pack(side="right", fill="y")
    text = Text(frame1, font = ('Arial', 15),yscrollcommand=text_scroll.set)
    **text.image_create(END, image=img)**
    text_scroll.config(command=text.yview)
    text.insert(END,'\nGroup Net Meter Utility\n','center', 'big')
    with open('HelpDoc.txt', 'r') as f:
        text.insert(INSERT, f.read())
    text.config(state=NORMAL)
    text.pack(side=LEFT, fill=Y)

I want to use the Text widget because I want the most text-formatting flexibility. The next challenge is embedding formatting tags in the imported text document.

Thank you in advance.


Solution

  • You can configure a tag to center the indexes that have the tag. You can then apply this tag to the index of the image.

    Here's a simple example:

    import tkinter as tk
    
    root = tk.Tk()
    text = tk.Text(root)
    text.pack(fill="both", expand=True)
    
    text.tag_configure("center", justify="center")
    
    image = tk.PhotoImage(file="robot.png")
    text.image_create("1.0", image=image)
    text.tag_add("center", "1.0")
    
    root.mainloop()
    

    screenshot of centered image