Python3/Tkinter 文本“显示线"行为问题 [英] Python3/Tkinter text "displaylines" behavior issue

查看:31
本文介绍了Python3/Tkinter 文本“显示线"行为问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算文本框中预填充数据时使用的实际行数,以及提交表单时再次使用的行数.

I am trying to count the actual lines used in a text box when it is pre-filled with data, and again when the form is submitted.

在下面的代码中,它在开始时错误地将行数显示为字符 (93),但是当您按下计数按钮时,它显示了正确的行数 (4)..来自同一代码执行.我错过了什么?(我是在这里发帖的新手,放轻松.....)

With the code below, it incorrectly shows the number of lines as chars (93) when it starts, but when you push the count button it shows the correct number of lines (4).. from the same code execution. What am I missing? (I'm new to posting on here, go easy.....)

import tkinter

text="adfa asdfkljds ;das asdjfkds fkldjasf dsf;dlsjfdkls jdkls fjd;lsfjd;ls fjd;lsafj ;dlsfj;asdlf"

def countit():
    print(DE.count('1.0', 'end', 'displaylines')[0])

top = tkinter.Tk()

DE = tkinter.Text(top, height=5, width=30, wrap="word")
DE.pack()
DEButton = tkinter.Button(top, text="count", command=countit)
DEButton.pack()        # WHEN BUTTON IS PRESSED, CORRECT NUMBER IS DISPLAYED

DE.insert("1.0", text)
countit()              # FIRST RUN, INCORRECT NUMBER DISPLAYED

top.mainloop()

推荐答案

displaylines 如果不显示数据,则无法计算,因为该值取决于各种因素,例如屏幕分辨率,实际字体(可能与请求的字体不同),小部件的大小一次packplacegrid 并完成它的计算,等等.在窗口实际映射到屏幕之前无法确定这些.

displaylines can't be calculated if the data isn't displayed, since the value depends on various factors such as the screen resolution, the actual font (which might be different than the requested font), the size of the widget once pack, place, or grid and done it's calculations, and so on. These can't be determined until the window is actually mapped to the screen.

为了说明这一点,在调用 countit() 之前立即添加 top.update(),您将看到该值第一次正确打印.

To illustrate the point, add top.update() immediately before calling countit() and you'll see that the value is correctly printed the first time.

更好的解决方法是在窗口映射到屏幕之前不调用 countit.例如,您可以在创建文本小部件后添加这行代码:

A better fix would be to not call countit until the window has been mapped to the screen. For example, you can add this line of code after creating the text widget:

DE.bind("<Map>", lambda event: countit())

上面的代码将在小部件映射到屏幕后立即调用 countit().

The above will call countit() immediately after the widget has been mapped to the screen.

这篇关于Python3/Tkinter 文本“显示线"行为问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆