简体   繁体   English

Tkinter文本小部件的get()方法-不返回最后一个字符

[英]get() method of Tkinter text widget - doesn't return the last character

I'm writing some GUI program in Tkinter . 我正在Tkinter中编写一些GUI程序。 I'm trying to trace the contents of the Text widget by using Text.get() method. 我正在尝试使用Text.get()方法来跟踪Text小部件的内容。
I heard that I can get(1.0, 'end') to get current contents written on the widget, but it doesn't give the most recent character I typed. 我听说我可以get(1.0,'end')来将当前内容写在小部件上,但是它不提供我键入的最新字符。

This is a simple example I wrote: 这是我写的一个简单示例:

import Tkinter as tk

class TestApp(tk.Text, object):
    def __init__(self, parent = None, *args, **kwargs):
        self.parent = parent
        super(TestApp, self).__init__(parent, *args, **kwargs)

        self.bind('<Key>', self.print_contents)

    def print_contents(self, key):
        contents = self.get(1.0, 'end')
        print '[%s]' % contents.replace('\n', '\\n')

if __name__ == '__main__':
    root = tk.Tk()
    app = TestApp(root, width = 20, height = 5)
    app.pack()
    root.mainloop()

If I type 'abcd', it prints 'abc\\n', not 'abcd\\n'. 如果输入“ abcd”,它将显示“ abc \\ n”,而不是“ abcd \\ n”。 ('\\n' is automatically added after the last line by the Text widget.) (“ \\ n”由“文本”小部件自动添加到最后一行之后。)

例

How can I get 'abcd\\n', instead of 'abc\\n'? 如何获得“ abcd \\ n”而不是“ abc \\ n”?


[Solved] [解决了]

Thanks to Bryan Oakley and Yasser Elsayed , I solved the problem by replacing 感谢Bryan OakleyYasser Elsayed ,我通过替换解决了问题

self.bind('<Key>', self.print_contents)

to the following: 到以下内容:

self.bind('<KeyRelease>', self.print_contents)

例子2

This is due to the timing of your event handler, which executes as soon as the event happens, meaning there was no chance for the Text widget to actually get the key typed just yet. 这是由于事件处理程序的时间安排,事件处理程序会在事件发生后立即执行,这意味着“文本”小部件尚没有机会真正获得键入的键。 You have two options here, either simply append the key parameter you get in the event handler to the Text.get() result, or bind to <KeyRelease-A> for example if you're listening for a specific key ( A in this case). 您在此处有两个选择,或者只是将在事件处理程序中获得的key参数附加到Text.get()结果中,或者将其绑定到<KeyRelease-A> ,例如,如果您正在侦听特定的key(在本例中为A案件)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM