【问题标题】:Smooth output from root.bind key从 root.bind 键平滑输出
【发布时间】:2022-09-28 04:13:01
【问题描述】:

如果您使用 Root.bind 获取键输入并添加它将执行的功能,它将执行它,稍作停顿,然后继续快速执行它但是如何在不暂停的情况下执行它,如果有是一种检测它是否被单击(未释放)然后开始执行它并且当按钮被抬起时它将停止执行它的方法? (不使用另一个导入,它不工作,为什么)

from tkinter import *

A = 0

def fun(event):
    global A
    if event.keysym == \'space\':
        A += 1
        print(A)

root = Tk()

root.bind(\"<Key>\", fun)
root.mainloop()
  • 请提供足够的代码,以便其他人更好地理解或重现问题。
  • 你只是按住一个键吗?那可能是操作系统或键盘进行自动重复。 tkinter 无法控制。这听起来可能是xy 问题。你想解决什么问题?
  • 我不知道这是否有帮助,但如果您只关心space 键,您可以在绑定中使用\'&lt;Key-space&gt;\' 而不仅仅是\'&lt;Key&gt;\'。这样一来,您的绑定函数就不会在每次按键时不必要地触发,您也不需要if event.keysym == \'space\'。但是,这不会忽略来自保持键的键重复。一个简单的方法是改用\'&lt;KeyRelease-space&gt;\'

标签: python tkinter input


【解决方案1】:

我想我理解这个问题。您想按住空格键并在按住空格键时执行某些操作,并在释放键后停止。

&lt;Key&gt; 绑定检测按键按下,然后每次重复按键按下。

&lt;KeyRelease&gt; 绑定检测每个键重复的键释放以及实际释放键的时间。

在下面的代码中,fun_on 在每个 Key 事件之后执行,fun_off 在每个 KeyRelease 事件之后执行。

import tkinter as tk

A = 0
cycle = False

def fun_off( event ):
    global timer

    def on_after():
        """ This executes 1 ms after it's triggered.
        If a <Key> event is detected during the millisecond it's cancelled.
        See fun_on """
        global A, cycle
        A = 0
        cycle = False

    timer = root.after( 1, on_after ) # More milliseconds may be
                                      # needed for some hardware

def do_cycle(): # This executes as long as cycle is True
    global A
    if cycle: 
        A += 1
        print( A )
        root.after( 10, do_cycle )  # Set ms delay as required.

def fun_on(event):
    """ Cancels the after ID from fun_off. 
        My auto repeat executes key down 0.1 ms after key up.
        This will cancel the after function unless the key is actually released"""
    global cycle

    root.after_cancel( timer )
    if not cycle:
        cycle = True
        do_cycle()

root = tk.Tk()

timer = root.after( 0, lambda: None ) # Makes timer a validafter id. 

root.bind( "<KeyRelease-space>", fun_off )
root.bind( "<Key-space>", fun_on )

root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多