Tkinterでクリップボード

[pukiwiki]
今週は雨が多いみたいですね
*[[gifmaker2.py 修正:http://boxheadroom.com/2009/05/20/py_animated_gif]]
gifアニメ作成用モジュールにバグを見つけたので修正しました
*Tkinterからクリップボード
Pythonに標準装備されてるGUI、Tkinterからクリップボードを読み書きする方法を知ったのでメモ。
[/pukiwiki]

[pukiwiki]
Tkinter.Textオブジェクトのメソッド
-clipboard_append
-clipboard_get
-clipboard_clear

を使って操作します。
参考 [[Tk.Text の使い方 :http://www.shido.info/py/tkinter12.html]]

blogに貼り付けるPythonのスクリプト中の\などを実体参照に置換して、クリップボードへ保存します。

[/pukiwiki]

# -*- coding: utf-8 -*-
import Tkinter as tk

replace_pair= [["&","&"],[">",">"],
                ["<","&lt;"],["\\","&#x5c;"]]
def rep(event=None):
    t=text.get("1.0",tk.END)
    for old,nw in replace_pair :
        t=t.replace(old,nw)
    text.delete("1.0",tk.END)
    text.insert("1.0",t)
    text.clipboard_append(t)
root=tk.Tk()
text=tk.Text()
text.insert("1.0",text.clipboard_get())
rep()

btn1=tk.Button(root,text="置換",command=rep)

btn2=tk.Button(root,text="クリア",
    command=lambda ev=None:text.delete("1.0",tk.END))
btn1.grid(row=0,column=0)
btn2.grid(row=0,column=1)

text.grid(row=1,column=0,columnspan=2)
root.mainloop()


コメントを残す

メールアドレスが公開されることはありません。