2 回答
TA贡献1785条经验 获得超4个赞
我认为这个问题与打印键值有关。当您在按钮单击时捕获按键并将其打印在 textview 上时,您正在传递键值
def on_key_down(self, widget, event, data=None):
keyval = event.keyval
keyname = Gdk.keyval_name(keyval)
self.textbuffer.insert_at_cursor(keyname+'\n')
在此函数中,当您尝试打印 @ 之类的特殊字符时,它将打印“at”作为其键名。要打印由此按键产生的文本,您必须将其更改为
self.textbuffer.insert_at_cursor(event.string+'\n')
https://developer.gnome.org/gdk3/stable/gdk3-Event-Structures.html#GdkEventKey
或者作为替代方案,您可以将 keyevent 传播到 textview
https://developer.gnome.org/gtk3/stable/GtkWindow.html#gtk-window-propagate-key-event https://developer.gnome.org/gtk3/stable/chap-input-handling.html
TA贡献1829条经验 获得超13个赞
``import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="awesome gui")
self.set_resizable(True)
self.set_default_size(700, 550)
self.grid = Gtk.Grid()
self.add(self.grid)
self.create_textview()
self.create_buttons()
self.buffer = []
def create_textview(self):
scrolledwindow = Gtk.ScrolledWindow()
scrolledwindow.set_hexpand(True)
scrolledwindow.set_vexpand(True)
self.grid.attach(scrolledwindow, 0, 2, 80, 1)
self.textview = Gtk.TextView()
scrolledwindow.add(self.textview)
self.textbuffer = self.textview.get_buffer()
self.textview.set_editable(False)
self.textview.set_cursor_visible(False)
def create_buttons(self):
self.button1 = Gtk.Button(label="Clear text")
self.button1.connect("clicked", self.on_button1_clicked)
self.grid.attach(self.button1, 0, 0, 1, 1)
self.button2 = Gtk.Button(label="Start capturing")
self.button2.connect("key-release-event", self.on_key_release)
self.button2.connect("key-press-event", self.on_key_down)
self.grid.attach_next_to(self.button2, self.button1, Gtk.PositionType.RIGHT, 1, 1)
def on_button1_clicked(self, widget):
self.textbuffer.set_text('')
def on_key_release(self, widget, event, data=None):
keyval = event.keyval
keyname = Gdk.keyval_name(keyval)
if keyname in self.buffer:
self.buffer.remove(keyname)
if self.buffer:
self.textbuffer.insert_at_cursor('you released '+'+'.join(self.buffer)+'\n')
def on_key_down(self, widget, event, data=None):
keyval = event.keyval
keyname = Gdk.keyval_name(keyval)
ctrl = (event.state & Gdk.ModifierType.CONTROL_MASK)
shift = (event.state & Gdk.ModifierType.SHIFT_MASK)
mod1 = (event.state & Gdk.ModifierType.MOD1_MASK)
super = (event.state & Gdk.ModifierType.SUPER_MASK)
hyper = (event.state & Gdk.ModifierType.HYPER_MASK)
meta = (event.state & Gdk.ModifierType.META_MASK)
lock = (event.state & Gdk.ModifierType.LOCK_MASK)
if keyname in 'AĄzżółćgęśaą' and keyname and (shift or mod1 or ctrl or super or hyper or meta or lock) not in self.buffer:
self.buffer.append(keyname)
if self.buffer:
self.textbuffer.insert_at_cursor('you pressed '+'+'.join(self.buffer)+'\n')
win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()``
添加回答
举报