我正在编写自己的代码编辑器,我希望它的左侧有编号的行。基于this answer我写了这个示例代码:
#!/usr/bin/env python3
import tkinter
class CodeEditor(tkinter.Frame):
def __init__(self, root):
tkinter.Frame.__init__(self, root)
# Line numbers widget
self.__line_numbers_canvas = tkinter.Canvas(self, width=40, bg='#555555', highlightbackground='#555555', highlightthickness=0)
self.__line_numbers_canvas.pack(side=tkinter.LEFT, fill=tkinter.Y)
self.__text = tkinter.Text(self)
self.__text['insertbackground'] = '#ffffff'
self.__text.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=True)
def __update_line_numbers(self):
self.__line_numbers_canvas.delete("all")
i = self.__text.index('@0,0')
self.__text.update() #FIX: adding line
while True:
dline = self.__text.dlineinfo(i)
if dline:
y = dline[1]
linenum = i[0]
self.__line_numbers_canvas.create_text(1, y, anchor="nw", text=linenum, fill='#ffffff')
i = self.__text.index('{0}+1line'.format(i)) #FIX
else:
break
def load_from_file(self, path):
self.__text.delete('1.0', tkinter.END)
f = open(path, 'r')
self.__text.insert('0.0', f.read())
f.close()
self.__update_line_numbers()
class Application(tkinter.Tk):
def __init__(self):
tkinter.Tk.__init__(self)
code_editor = CodeEditor(self)
code_editor.pack(fill=tkinter.BOTH, expand=True)
code_editor.load_from_file(__file__)
def run(self):
self.mainloop()
if __name__ == '__main__':
app = Application()
app.run()
不幸的是,__update_line_numbers 中出了点问题。此方法应在我的 Canvas 小部件上从上到下写入行号,但它仅打印第一行 (1) 的行号,然后退出。为什么?
请您参考如下方法:
根本问题是您正在调用 dlineinfo在返回到 runloop 之前,所以文本还没有被布局。
作为the docs解释:
This method only works if the text widget is updated. To make sure this is the case, you can call the update_idletasks method first.
像往常一样,要获得更多信息,您必须求助于 Tcl docs for the underlying object ,它基本上告诉您文本小部件在更新之前可能不正确关于哪些字符可见和不可见,在这种情况下它可能会返回 None。不是因为任何问题,而是因为,就它而言,你要求的是屏幕外的东西的 bbox。
测试这是否是问题所在的一个好方法是调用 self.__text.see(i)打电话前 dlineinfo(i) .如果它改变了 dlineinfo 的结果,这就是问题所在。 (或者,如果不是那样,至少与此相关——无论出于何种原因,Tk 认为第 1 行之后的所有内容都在屏幕外。)
但在这种情况下,即使调用 update_idletasks不起作用,因为它不仅更新需要发生的行信息,而且首先布置文本。您需要做的是明确推迟此调用。例如,将此行添加到 load_from_file 的底部现在它起作用了:
self.__text.after(0, self.__update_line_numbers)
您也可以调用 self.__text.update()打电话前 self.__update_line_numbers()内联,我认为这应该有效。
作为旁注,它真的可以帮助您在调试器下运行它,或者添加一个 print(i, dline)在循环的顶部,这样你就可以看到你得到了什么,而不仅仅是猜测。
另外,增加一个 linenumber 不是更容易吗?并使用 '{}.0'.format(linenumber)而不是创建像 @0,0+1line+1line+1line 这样的复杂索引那(至少对我而言)不起作用。您可以调用Text.index()将任何索引转换为规范格式,但为什么如此困难?你知道你想要的是1.0 , 2.0 , 3.0等等,对吧?
