首页 > 解决方案 > 如何使两台印刷机在 tkinter 中产生相同的输出

问题描述

我想制作一个将两个输入绑定到一个输出的 Tkinter 程序我试过这个:

def hh(event):
      print('hello')
root.bind(<Returna>, hh)

def hh(event):
    print('hello')
root.bind('<Return, KeyPress-a>')

但它没有按预期工作。有人可以告诉我如何制作<Shift><KeyPress-a>一起触发hh()吗?谢谢!

第一个错误

Traceback (most recent call last):
  File "tktest.py", line 19, in <module>
    root.bind('<Returna>', hh)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/`__init__.`py", line 1251, in bind
    return self._bind(('bind', self._w), sequence, func, add)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/`__init__`.py", line 1206, in _bind
    self.tk.call(what + (sequence, cmd))
_tkinter.TclError: bad event type or keysym "Returna" 

第二个错误

Traceback (most recent call last):  
  File "tktest.py", line 19, in <module>  
    root.bind('<Return, KeyPress-a>', hh)  
  File  "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1251, in bind  
    return self._bind(('bind', self._w), sequence, func, add)  
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1206, in _bind  
    self.tk.call(what + (sequence, cmd))  
_tkinter.TclError: bad event type or keysym "Return,"  

标签: pythontkinterbinding

解决方案


您必须使用字符串'<Return>a'并添加函数名称

root.bind('<Return>a', hh)

但是当您直接hh()按下后它会运行aEnter


import tkinter as tk

def hh(event):
      print('hello')

root = tk.Tk()
root.bind('<Return>a', hh)
root.mainloop()

如果您想hh()在按EnterOR时运行,a那么您需要两个绑定

root.bind('<Return>', hh)
root.bind('a', hh)

import tkinter as tk

def hh(event):
      print('hello')

root = tk.Tk()
root.bind('<Return>', hh)
root.bind('a', hh)
root.mainloop()

编辑:

在已编辑的问题中,我看到<Shift>了,所以也许必须如此Shift + a?它需要A

root.bind('A', hh) # Shift + a

在我看到的第二个错误中,Return,但也许它必须是Shift + ,具有特殊名称的<less>

root.bind('<less>', hh) # Shift + , 

在 asnwer 到.bind() 不适用于 shift 键绑定?我展示了显示keysym按键的代码以及您可以在其中使用的代码bind()

import tkinter as tk

def test(event):
    print('keysym:', event.keysym)

root = tk.Tk()
root.bind('<Key>', test)
root.mainloop()

您可以在文档Tcl/Tk -keysym中找到一些名称

但是or并没有什么特别之处keysym,因为它是不寻常的组合,可能需要按住/再按or 。或按下、松开,然后按下或Return + aReturn + ,ReturnEntera,ReturnReturna,


推荐阅读