我正在开发一个应用程序来编辑脱氧核糖核酸序列,我想有一个tkinter文本小工具,其中只能输入字母atgcATGC。
有什么简单的方法可以做到吗?
谢谢,大卫
发布于 2011-07-02 03:35:36
我终于找到了一种方法来获得我想要的行为:
from Tkinter import Text, BOTH
import re
class T(Text):
def __init__(self, *a, **b):
# Create self as a Text.
Text.__init__(self, *a, **b)
#self.bind("<Button-1>", self.click)
self.bind("<Key>", self.key)
self.bind("<Control-v>", self.paste)
def key(self,k):
if k.char and k.char not in "atgcATGC":
return "break"
def paste(self,event):
clip=self.selection_get(selection='CLIPBOARD')
clip=clip.replace("\n","").replace("\r","")
m=re.match("[atgcATGC]*",clip)
if m and m.group()==clip:
self.clipboard_clear()
self.clipboard_append(clip)
else:
self.clipboard_clear()
return
t = T()
t.pack(expand=1, fill=BOTH)
t.mainloop()发布于 2011-06-29 02:25:44
您可以使用Entry小部件的validatecommand特性。我能找到的最好的文档是关于类似问题的this answer。按照这个例子,
import Tkinter as tk
class MyApp():
def __init__(self):
self.root = tk.Tk()
vcmd = (self.root.register(self.validate), '%S')
self.entry = tk.Entry(self.root, validate="key",
validatecommand=vcmd)
self.entry.pack()
self.root.mainloop()
def validate(self, S):
return all(c in 'atgcATGC' for c in S)
app=MyApp()发布于 2011-06-29 02:13:00
您必须在输入文本的小部件上捕获"<Key>"事件。然后你就可以过滤掉
if key.char and key.char not in "atgcATGC":
return "break"这里有一些关于在tkinter中处理事件的信息:http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
https://stackoverflow.com/questions/6510950
复制相似问题