亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有“編程”輸入功能的 Python 文本編輯器

具有“編程”輸入功能的 Python 文本編輯器

元芳怎么了 2023-06-06 10:28:24
我需要一個文本編輯器,作為一項功能,它必須能夠在打開時更改它在屏幕上顯示的某些信息。例如,我使用上面提到的文本編輯器打開文本文件,我可以在屏幕上看到:|--------------------------------------------------------||          My Text Editor (C:\myfile.txt)    [Button]    ||--------------------------------------------------------||Name: John                                              ||Age: 32                                                 ||Gender: Male                                            ||                                                        | |                                                        |然后,例如,如果我點擊按鈕[Button],我希望在打開文本文件時將年齡 32 更改為 30。但我想在不使用鍵盤和鼠標自動化的情況下做到這一點......那可能嗎?Tkinter 足以完成這項任務嗎?
查看完整描述

2 回答

?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

這是一個人為的例子,它都有一個改變年齡的按鈕,并且每秒都會更新一次時間。

它使用上下文管理器執行此操作,該管理器保留插入光標,然后插入或刪除您想要的任何文本。這不是特別好的編碼風格,但它顯示了 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()

您無法從靜態屏幕截圖中分辨出來,但如果您運行代碼,您會看到時間會實時更新,即使您正在鍵入。

http://img4.sycdn.imooc.com/647e99e90001d88905450348.jpg

查看完整回答
反對 回復 2023-06-06
?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

我認為,實現此目的的最佳方法是采用 PyQT 的簡單 TextEditor 示例并添加一個按鈕來執行您想要的操作。

查看完整回答
反對 回復 2023-06-06
  • 2 回答
  • 0 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號