![](/img/trans.png)
[英]How to open and manipulate multiple text files all at the same time after selecting them with tkinter?
[英]Selecting multiple text in tkinter
有沒有辦法在 tkinter 中 select 多個文本?
這是代碼:
from tkinter import *
root = Tk()
text = Text(root , width = 65 , height = 20 , font = "consolas 14")
text.pack()
text.insert('1.0' , "This is the first line.\nThis is the second line.\nThis is the third line.")
mainloop()
在這里,我希望能夠從我想要的任何地方 select 多個文本。
這是一個解釋我的意思的圖像(GIF):
有沒有辦法在 tkinter 中實現這一點?
如果有人可以幫助我,那就太好了。
我做了一個簡短的演示,按住Control
鍵可以 select 多個文本。 檢查這個:
import tkinter as tk
class SelectableText(tk.Text):
def __init__(self, master, **kwarg):
super().__init__(master, **kwarg)
self.down_ind = ''
self.up_ind = ''
self.bind("<Control-Button-1>", self.mouse_down)
self.bind("<B1-Motion>", self.mouse_drag)
self.bind("<ButtonRelease-1>", self.mouse_up)
self.bind("<BackSpace>", self.delete_)
def mouse_down(self, event):
self.down_ind = self.index(f"@{event.x},{event.y}")
def mouse_drag(self, event):
self.up_ind = self.index(f"@{event.x},{event.y}")
if self.down_ind and self.down_ind != self.up_ind:
self.tag_add(tk.SEL, self.down_ind, self.up_ind)
self.tag_add(tk.SEL, self.up_ind, self.down_ind)
def mouse_up(self, event):
self.down_ind = ''
self.up_ind = ''
def delete_(self, event):
selected = self.tag_ranges(tk.SEL)
if len(selected) > 2:
not_deleting = ''
for i in range(1, len(selected) - 1):
if i % 2 == 0:
not_deleting += self.get(selected[i-1].string, selected[i].string)
self.delete(selected[0].string, selected[-1].string)
self.insert(selected[0].string, not_deleting)
return "break"
root = tk.Tk()
text = SelectableText(root, width=50, height=10)
text.grid()
text.insert('end', "This is the first line.\nThis is the second line.\nThis is the third line.")
root.mainloop()
所以我試圖用Text.delete(index1, index2)
刪除每個選擇,但是當一行中的第一個選擇被刪除時,索引會發生變化,從而導致后續delete
刪除索引未被選中(或超出特定行中的范圍) .
我不得不解決另一種方法 - 首先從第一個選擇到最后一個選擇刪除,就像BackSpace
默認會執行的操作,然后將每個未選擇的部分放回中間。 Text.tag_ranges
為您提供以這種方式選擇的范圍列表:
[start1, end1, start2, end2, ...]
其中每個條目都是具有string
屬性(索引)的<textindex object>
。 因此,您可以提取end1
和start2
之間、 end2
和start3
之間的文本等到最后,並將它們存儲到一個變量( not_deleting
)中,這樣您就可以將它們重新插入到文本中。
應該有更好和更整潔的解決方案,但現在就是這樣......希望它有所幫助。
簡短回答:將每個 Text 小部件的exportselection
屬性設置為False
Tkinter 讓您可以使用 Text 小部件以及 Entry 和 Listbox 小部件的exportselection
配置選項來控制此行為。 將其設置為False
可防止將選擇導出到 X 選擇,從而允許小部件在不同的小部件獲得焦點時保留其選擇。
例如:
import tkinter as tk
...
text1 = tk.Text(..., exportselection=False)
text2 = tk.Text(..., exportselection=False)
你可以在這里找到更多信息: http://tcl.tk/man/tcl8.5/TkCmd/options.htm#M-exportselection
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.