Tkinter文本框限制可用字符数

2 投票
4 回答
1929 浏览
提问于 2025-04-16 20:28

我正在开发一个用来编辑DNA序列的应用程序,我想要一个tkinter的文本框,里面只能输入字母atgc和ATGC。

有没有简单的方法可以做到这一点呢?

谢谢,
大卫

4 个回答

1

你需要在你输入文本的控件上捕捉到 "<Key>" 这个事件。然后你可以进行筛选。

if key.char and key.char not in "atgcATGC":
    return "break"

这里有一些关于在 tkinter 中处理事件的信息:http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

3

你可以使用Entry控件的validatecommand功能。根据我找到的最好资料,可以参考这个回答,它是针对类似问题的解答。按照那个例子来做,

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()
2

我终于找到了一种方法,可以实现我想要的确切效果:

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()

撰写回答