最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Identical tkinter text widgets when font style and size is changed - Stack Overflow

programmeradmin0浏览0评论

I have a program that uses tkinter. There are two tkinter text widgets where the first one contains a sample text and the second one takes in a user input so that the user can type out the same sample text that is in the first text widget.

In this program, I am also trying to automatically insert a \n in the string of the sample text every certain number of characters, in this case every 10 characters, in such a way that the first text widget that contains the sample text does not have any words overlapping between two lines. So I used the textwrap.wrap() method like so:

import tkinter as ttk
import textwrap

a_string = "This is a line and another line and more lines further lines"
a_string = textwrap.wrap(text=a_string, width=10, drop_whitespace=False) # Creates a list with 10
# characters per string element unless the string element has to be a made shorter to prevent a word
# overlapping between one string element and the next

for num in range(0,len(a_string)):
    a_string[num] = a_string[num]+"\\n"
a_string = "".join(a_string)
a_string = a_string.replace("\\n","\n")

window = ttk.Tk()
window.minsize(width=200, height=100) 

txt = ttk.Text(
    window,
    wrap=ttk.WORD, 
    width = 10, # 10 characters per line
    height=10, 
)
txt.insert(
    "1.0",
    a_string,
)
txt.grid(
    pady=10,
    padx=10,
)

user_input = ttk.Text(
   window,
    wrap=ttk.WORD,
    width = 10, # 10 characters per line
    height=10,
)
user_input.grid(
    pady=10,
    padx=10,
)

window.mainloop()

Which gives the following after the user types the same text in the second widget (Note the text in both widgets below are not 100% identical because there is “ further” in the first widget whereas there is “further” in the second widget):

Now, when I change the font style and size of both text widgets like so:

txt = ttk.Text(
    window,
    font="Arial 14", # Font style and size
    wrap=ttk.WORD, 
    width = 10, # 10 characters per line
    height=10,
)
txt.insert(
    "1.0",
    a_string,
)
txt.grid(
    pady=10,
    padx=10,
)

user_input = ttk.Text(
    window,
    font="Arial 14", # Font style and size
    wrap=ttk.WORD,
    width = 10, # 10 characters per line
    height=10,
)
user_input.grid(
    pady=10,
    padx=10,
)

The number of characters per line in both widgets are no longer the same since the second widget takes in more than 10 characters per line even though I specified the width of both text widgets to be 10:

So my question is: how can I ensure that both widgets have exactly the same amount of characters per line and look exactly identical even if the font style and size is changed?

发布评论

评论列表(0)

  1. 暂无评论