首页 > 解决方案 > 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')

标签: pythonuser-interfacetkinter

解决方案


这里有几点需要注意——

  • txt.insert('0.1', ....)-> 这个 0.1 不是一个有效的索引(虽然它确实有效,但使用 '1.0' 这意味着将此文本放在第 1 行,字符位置 0 - 仅表示文本小部件的开始)。索引需要是一个常数(比如tk.END-tktkinter这里),或者是一个形式的值,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位置的字符)
该方法有两个重要参数。index1index2-index1表现得像startindexindex2表现得像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)返回小部件的完整文本。

但是如果你省略index2or 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()

推荐阅读