Pythonのtkinterでは、マウスでテキストを選択できるようにLabelを作成するにはどうすればよいですか?
質問
Pythonのtkinterインターフェイスには、ラベル内のテキストを選択してクリップボードにコピーできるようにラベルを変更する構成オプションがありますか?
編集:
この「こんにちは世界」をどのように変更しますかこのような機能を提供するアプリですか?
from Tkinter import *
master = Tk()
w = Label(master, text="Hello, world!")
w.pack()
mainloop()
解決
最も簡単な方法は、高さが1行の無効なテキストウィジェットを使用することです。
from Tkinter import *
master = Tk()
w = Text(master, height=1, borderwidth=0)
w.insert(1.0, "Hello, world!")
w.pack()
w.configure(state="disabled")
# if tkinter is 8.5 or above you'll want the selection background
# to appear like it does when the widget is activated
# comment this out for older versions of Tkinter
w.configure(inactiveselectbackground=w.cget("selectbackground"))
mainloop()
同様の方法でエントリウィジェットを使用できます。
他のヒント
上記のコードにいくつかの変更を加えます:
from tkinter import *
master = Tk()
w = Text(master, height=1)
w.insert(1.0, "Hello, world!")
w.pack()
# if tkinter is 8.5 or above you'll want the selection background
# to appear like it does when the widget is activated
# comment this out for older versions of Tkinter
w.configure(bg=master.cget('bg'), relief=FLAT)
w.configure(state="disabled")
mainloop()
レリーフは、ディスプレイの通常の部分のように見えるように平らである必要があります。 :)
Text
または Entry
を使用して選択可能なテキストを作成できます。
両方とも本当に便利だと思うので、テキストを使うと本当に便利です!ここにエントリーのコードを示します:
from tkinter import *
root = Tk()
data_string = StringVar()
data_string.set("Hello World! But, Wait!!! You Can Select Me :)")
ent = Entry(root,textvariable=data_string,fg="black",bg="white",bd=0,state="readonly")
ent.pack()
root.mainloop()
所属していません StackOverflow