Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can separate text block in Python application?

I'm learning Python and writing an application that should show text blocks on the screen. I'm using the tkinter library.

Text in some blocks may not fit in one line, so I've decided to use Text widget because it has the option of wrapping text. And I've also used Scrollbar widget because text blocks may not fit the screen. So my code looks like this:

root = Tk()
scrollbar = Scrollbar(root)
t = Text(root, wrap=WORD)

def show_messages():
    for i in range (0, len(messages)):
         t.insert(END, messages[i] + '\n')

def show_windows():
    scrollbar.pack(side="right", fill="y", expand=False)
    t.pack(side="left", fill="both", expand=True)
    root.mainloop()

show_messages()
show_window() 

And, after all, the messages should be separated with some kind of line, but I'm stuck on this. So, my question is: how can I separate my text blocks? Or maybe I'm going down the wrong path, and I should use Listbox widget instead of Text? Thanks in advance!

like image 346
7duck Avatar asked Dec 14 '25 02:12

7duck


1 Answers

You can do it by inserting a black frame using the window_create method of the Text widget:

import tkinter as tk

root = tk.Tk()
scrollbar = tk.Scrollbar(root)
t = tk.Text(root, wrap="word")

messages = [
"""
#############################
#                           #
#       text block 1        #
#                           #
#############################
""",
"""
#############################
#                           #
#       text block 2        #
#                           #
#############################
"""
]

def show_messages():
    for i in range (0, len(messages)):
         t.insert("end", messages[i] + '\n')
         # add a black centered the text block
         f = tk.Frame(t, width=200, height=1, background="black")
         t.window_create("end", window=f)
         t.insert("end",'\n')

def show_windows():
    scrollbar.pack(side="right", fill="y", expand=False)
    t.pack(side="left", fill="both", expand=True)
    root.mainloop()

show_messages()
show_windows()
like image 162
j_4321 Avatar answered Dec 15 '25 17:12

j_4321



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!