如何解决具有“以编程方式”键入功能的Python文本编辑器
我需要一个文本编辑器,作为一个功能,它必须具有在打开时更改屏幕上显示的某些信息的功能。
例如,我使用上述文本编辑器打开文本文件,然后在屏幕上看到:
|--------------------------------------------------------|
| My Text Editor (C:\myfile.txt) [Button] |
|--------------------------------------------------------|
|Name: John |
|Age: 32 |
|Gender: Male |
| |
| |
然后,例如,如果我按下按钮[Button]
,我希望在打开文本文件的同时将Age 32更改为30。
但是我想不使用键盘和鼠标自动化...
有可能吗? Tkinter足够完成这项任务吗?
解决方法
这是一个人为的示例,它们都有一个按钮来更改年龄,并且还会每秒更新一次时间。
它用context manager进行此操作,它保留插入光标,然后插入或删除所需的任何文本。这不是特别好的编码样式,但它显示了tkinter可以使用其文本小部件做什么。
import tkinter as tk
from datetime import datetime
from contextlib import contextmanager
@contextmanager
def preserve_insert_cursor(text):
"""Performs an action without changing the insertion cursor location"""
saved_insert = text.index("insert")
yield
text.mark_set("insert",saved_insert)
def change_age():
"""Change the age on line 3"""
with preserve_insert_cursor(text):
text.delete("3.5","3.0 lineend")
text.insert("3.5","30")
def update_time():
with preserve_insert_cursor(text):
# find all ranges of text tagged with "time" and replace
# them with the current time
now = datetime.now()
timestring = now.strftime("%H:%M:%S")
ranges = list(text.tag_ranges("time"))
while ranges:
start = ranges.pop(0)
end = ranges.pop(0)
text.delete(start,end)
text.insert(start,timestring,"time")
# call this function again in a second
text.after(1000,update_time)
root = tk.Tk()
header = tk.Frame(root,bd=1,relief="raised")
text = tk.Text(root)
header.pack(side="top",fill="x")
text.pack(fill="both",expand=True)
button = tk.Button(header,text="Button",command=change_age)
button.pack(side="right",padx=10)
# insert "Time:" with no tags,"<time>" with the tag "time",# and then a newline with no tags
text.insert("end","Time: ","","<time>","time","\n")
text.insert("end","Name: John\n")
text.insert("end","Age: 32\n")
text.insert("end","Gender: Male\n")
update_time()
root.mainloop()
您无法从静态屏幕截图中分辨出来,但是如果您运行代码,则即使输入内容,时间也会实时更新。
,我认为,实现此目标的最佳方法是为PyQT举一个简单的TextEditor示例,并添加一个按钮来执行您想要的操作。
在快速搜索中,我找到了以下示例: https://www.learnpyqt.com/examples/no2pads-simple-notepad-clone/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。