Home > Blockchain >  Python how to press the #2 key twice and perform a separate action each time after press?
Python how to press the #2 key twice and perform a separate action each time after press?

Time:12-26

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) root.mainloop()

I would like this code to run in a loop and for me to press the #2 key and each time it performs a separate action not similar to the first key press. I appreciate any and all help and thank you ahead of time!

CodePudding user response:

This sounds like a reasonable case for a state machine. A state machine allows you to based your next response on all of the previous inputs. Basically, you have to decide how many different states (different ways of interpreting the input) and what to do with all the different possible inputs in each of those cases.

I don't have a ton of time to write more, but here's a link to a Wikipedia article about state machines: https://en.wikipedia.org/wiki/Finite-state_machine

I would start there and see if you can figure out how something like that can help you. Maybe also look for some more tutorial descriptions. Good luck!

CodePudding user response:

declare a boolean variable, and toggle it when first action runs. code would be like:

my_switch = True

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

elif event.keysym == '2' && !(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.
  • Related