2 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是一個(gè)人為的例子,它都有一個(gè)改變年齡的按鈕,并且每秒都會(huì)更新一次時(shí)間。
它使用上下文管理器執(zhí)行此操作,該管理器保留插入光標(biāo),然后插入或刪除您想要的任何文本。這不是特別好的編碼風(fēng)格,但它顯示了 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()
您無法從靜態(tài)屏幕截圖中分辨出來,但如果您運(yùn)行代碼,您會(huì)看到時(shí)間會(huì)實(shí)時(shí)更新,即使您正在鍵入。

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
我認(rèn)為,實(shí)現(xiàn)此目的的最佳方法是采用 PyQT 的簡(jiǎn)單 TextEditor 示例并添加一個(gè)按鈕來執(zhí)行您想要的操作。
添加回答
舉報(bào)