如何为Tkinter文本小部件添加书签?

2024-06-01 00:47:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本小部件,里面有一些文本。我想添加一个简单的书签(by Y)而不使用文本索引(例如“50.2”)。我该怎么做?你知道吗

我试过:

from tkinter import *


bookmarks = []  # create a list for bookmarks

def add_bookmark():
    bookmark = textbox.yview()  # get the vertical position of the view
    bookmarks.append(bookmark)  # and add it to the bookmarks' list

def goto_bookmark(bookmark):
    textbox.yview_moveto(bookmark)  # set the vertical positionn of the view

root = Tk()  # create a root window

# set the column's and row's weight
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

textbox = Text(root)  # create the Text widget
scrollbar = Scrollbar(root, command=textbox.yview)  # create the Scrollbar widget, and attach it to the Text widget
textbox["yscrollcommand"] = scrollbar.set  # attach the Text widget to the Scrollbar
# show the widgets using grid geometry manager
textbox.grid(row=0, column=0, sticky="nswe")
scrollbar.grid(row=0, column=1, sticky="nswe")
Button(root, text="Add bookmark", command=add_bookmark).grid()  # create and show the "Add bookmark" button
Button(root, text="Goto lastbookmark", command=lambda: goto_bookmark(bookmarks[-1])).grid()  # create and show the "Goto last bookmark" button

textbox.insert(END, "TEXT\n" *1000)  # fill the textbox with something

root.mainloop()  # start the mainloop

但是当我尝试去书签的时候有个例外:

_tkinter.TclError: expected floating-point number but got "0.7501873126873126 0.7741633366633367"


Tags: andthetotext文本addcreateroot
2条回答

首先,您应该调试代码,并确保负责关闭设备节点的线程确实关闭了它;因为您谈论的是对不可共享硬件设备的访问,所以在RXTX连接中使用Holder模式可能会有所帮助

如果程序没有正确地关闭设备节点,唯一的选择就是杀死它。您可以使用fuser /dev/ttyUSB0查看哪个进程打开了它,然后kill查看该PID。这不需要root权限,只需要以拥有要终止的进程的用户的身份访问

几个月前,我在工作中确实遇到了这个问题(至少看起来很像)。我花了很多时间(大约一周)在上面。我查看了本机代码,发现了问题(在RXTX库中)

我将建议您实现与我相同的解决方案——正确管理线程和端口您不应该依赖PortinUseeException来检查端口是否已打开——这是针对“例外”情况的

只要确保你:

  1. 始终在打开的端口上呼叫close
  2. 不要在打开的端口上调用open

如果你更愿意解决这个问题,而不是用正确的方法来解决这个问题,那么问题就出在本机应用程序中,所以你需要找到一种方法来“重启”它。在我的例子中,它都在一个OSGi框架内,所以我可以卸载包含本机应用程序的捆绑包,然后再次安装它。在您的情况下,可能需要重新启动整个Java进程

相关问题 更多 >