gpt4 book ai didi

python - 如何过滤或限制在 PyGTK 文本输入字段中输入的文本?

转载 作者:行者123 更新时间:2023-11-28 20:53:19 24 4
gpt4 key购买 nike

我想要一个仅接受十六进制字符作为用户有效输入的文本输入字段 (gtk.Entry)。

最佳答案

过滤可以通过连接到“insert_text”信号并在信号处理程序中操作输入的文本来完成。
下面是验证十六进制字符的示例代码:

#!/usr/bin/env python
import gtk, pygtk, gobject, string

class HexEntry(gtk.Entry):
"""A PyGTK text entry field which allows only Hex characters to be entered"""

def __init__(self):
gtk.Entry.__init__(self)
self.connect("changed", self.entryChanged)
self.connect("insert_text", self.entryInsert)

def entryChanged(self, entry):
# Called only if the entry text has really changed.
print "Entry changed"

def entryInsert(self, entry, text, length, position):
# Called when the user inserts some text, by typing or pasting.
print "Text inserted"

position = entry.get_position() # Because the method parameter 'position' is useless

# Build a new string with allowed characters only.
result = ''.join([c for c in text if c in string.hexdigits])

# The above line could also be written like so (more readable but less efficient):
# result = ''
# for c in text:
# if c in string.hexdigits:
# result += c

if result != '':
# Insert the new text at cursor (and block the handler to avoid recursion).
entry.handler_block_by_func(self.entryInsert)
entry.insert_text(result, position)
entry.handler_unblock_by_func(self.entryInsert)

# Set the new cursor position immediately after the inserted text.
new_pos = position + len(result)

# Can't modify the cursor position from within this handler,
# so we add it to be done at the end of the main loop:
gobject.idle_add(entry.set_position, new_pos)

# We handled the signal so stop it from being processed further.
entry.stop_emission("insert_text")

def main():
window = gtk.Window()
window.connect("delete-event", gtk.main_quit)
entry = HexEntry()
window.add(entry)
window.show_all()
gtk.main()

if __name__ == "__main__":
main()

关于python - 如何过滤或限制在 PyGTK 文本输入字段中输入的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5159219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com