python - python tkinter中的get()方法
问题描述
根据 get() 方法,它返回存在于方法的指定范围之间的字符串或startindex
字符endindex
。但是这里存在问题,因为我无法获取指定范围之间存在的字符串**
这是代码:
from tkinter import *
root = Tk()
txt = Text(root, spacing3 = 100, width = 50)
txt.insert('0.1',"My name is Abhishek Bhardwaj")
txt.pack()
#get() method of text widget
x = txt.get('5.7') **** This is a problem ****
print(x) **** This is a problem ****
root.mainloop()
在给定程序的输出中,没有所需的输出。这意味着 get() 方法的输出中没有字符串
如何通过使用带参数的 get() 方法从程序中获取所需的输出例如:-get('5.7')
解决方案
这里有几点需要注意——
txt.insert('0.1', ....)
-> 这个 0.1 不是一个有效的索引(虽然它确实有效,但使用 '1.0' 这意味着将此文本放在第 1 行,字符位置 0 - 仅表示文本小部件的开始)。索引需要是一个常数(比如tk.END
-tk
在tkinter
这里),或者是一个形式的值,x.y
其中 x 是行号,y 是该行上的字符位置号。txt.get('5.7')
将始终返回''
- 一个空字符串。因为这转换为Get the text at line 5, char position 7。您的文本小部件中没有第 5 行。
tk.Text.get() 方法
方法定义是.get(index1, index2=None)
(index2
不在inclusive
结果中,这意味着返回的文本不会包含该index2
位置的字符)
该方法有两个重要参数。index1
和index2
-index1
表现得像startindex
和index2
表现得像endindex
。这些索引中的每一个都需要是常量(如tk.END
)或x.y
形式中的值(如上所述)。
如果您同时传入两个参数,比如说 like .get('x.y', 'p.q')
,它会转换为 -获取第 x 行、第 y 行字符和第 p 行之间的文本。字符编号 q
如果您执行类似的操作.get('x.y', tk.END)
-您可以END
在此处使用,而不是tk.END
因为您在 tkinter 上使用了全局导入-它转换为在 x 行、字符编号 y 和文本小部件的结尾之间获取文本
这意味着使用.get('1.0', tk.END)
返回小部件的完整文本。
但是如果你省略index2
or endindex
,它将默认None
为 in .get(index1, index2=None)
。所以
txt.get('1.3')
将转换为txt.get(index1='1.3', index2=None)
,仅从'n'
第 1 行字符位置 3 的句子返回。
您的代码已修改:
from tkinter import *
root = Tk()
txt = Text(root, spacing3 = 100, width = 50)
txt.insert('1.0', "My name is Abhishek Bhardwaj")
txt.pack()
#get() method of text widget
x = txt.get('1.0', '1.5') # 1.3 is in form x.y where x being line number and y being char number ON THAT LINE
print(x)
root.mainloop()
推荐阅读
- java - 如何修复 application.yml 文件中的解析异常?
- wordpress - 获取WordPress中特定页面的最后修改日期
- java - 标记为只读的 PDComboBox 在 PDF 文档中不可见
- parallel-processing - 来自 RevoScaleR 的 rxExec 不会发生并行处理
- php - 如何在 Wordpress 模板上修复移动屏幕底部的按钮
- docusignapi - Dosusign API 访问令牌延长到期
- c# - For 循环增加文本框 ID。C# Windows 窗体
- ecmascript-5 - 在我的 tsconfig 中使用 es2017 作为库但将 es5 作为我的目标会使我的代码与 IE11 不兼容吗?
- python - 为什么在python类中设置方法在调用时不传递self?
- flutter - Flutter - 启用位置和动画相机到当前位置