Python中如何按#2键两次并在每次按下后执行一个单独的动作?

yqlxgs2m  于 2022-12-28  发布在  Python
关注(0)|答案(3)|浏览(145)

我想这段代码运行在一个循环,并为我按下#2键,每次它执行一个单独的行动不类似于第一次按下键。我感谢任何和所有的帮助,并提前感谢你!

from tkinter import *
root = Tk()
def key(event):
    if event.keysym == 'q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m':
        def read_number(path):
            print("do nothing")
    elif event.keysym =='2':
      print("Do first action")
        elif event.keysym =='2':
            print("Do another different action")
            # if event.keysym =='2':

root.bind_all('<Key>', key)
root.mainloop()
from tkinter import *
root = Tk()
def key(event):
    if event.keysym == 'q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m':
        def read_number(path):
            print("hi")
    elif event.keysym =='2':
        if event.keysym =='2':
            print("Do another action")
            # if event.keysym =='2':

root.bind_all('<Key>', key)
root.mainloop()
pgvzfuti

pgvzfuti1#

对于状态机来说,这听起来是一个合理的例子。状态机允许你基于所有先前的输入来做出下一个响应。基本上,你必须决定有多少种不同的状态(解释输入的不同方式),以及在每种情况下如何处理所有不同的可能输入。
我没有太多的时间来写更多的东西,但是这里有一篇关于状态机的Wikipedia文章的链接:https://en.wikipedia.org/wiki/Finite-state_machine
我会从那里开始,看看你是否能弄清楚这样的东西如何能帮助你。也许还会寻找一些更多的教程描述。祝你好运!

yc0p9oo0

yc0p9oo02#

from tkinter import *

root = Tk()

def get_action():
    """ A generator function to return an action from a list of actions.

    A generator retains its state after being called. It yields 1 item per
    call. For example range() is generator.
    Functions with return statements initialize their state at each call.
    """
    actions = ["Do another action", 'action1', 'action2', 'action3',
               'action4']
    for i in range(len(actions)):
        """ The value of i is incremented each call. """
        yield actions[i]

def key(event):
    # if event.keysym == 'q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m':
    # Changed the logic to display something when keys other than 2 are
    # pressed.
    if event.keysym in 'q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m':
        print("hi")
        def read_number(path):
            pass
    elif event.keysym == '2':
        try:
            print(next(action))
        except StopIteration:
            # Action to take after the generator is expended.
            print('No more actions.')

action = get_action()  # Bind the generator to a name
root.bind_all('<Key>', key)
root.mainloop()
e1xvtsh3

e1xvtsh33#

声明一个布尔变量,并在第一个操作运行时切换它。代码如下所示:

my_switch = True

elif event.keysym == '2' and my_switch:
  print("Do first action")
  my_switch = False

elif event.keysym == '2' and !(my_switch):
  print("Do second action")
  my_switch = True #only if you want the #2 key to have alternative functions, otherwise the key will do first action just once and then second one forever.

相关问题