The following is my short script. It is meant to print right left and up when those arrow keys are held, but I don’t know why it does not work.
import Tkinter as tk
right = False
left = False
up = False
def keyPressed(event):
if event.keysym == 'Escape':
root.destroy()
if event.keysym == 'Right':
right = True
if event.keysym == 'Left':
left = True
if event.keysym == 'Up':
up = True
def keyReleased(event):
if event.keysym == 'Right':
right = False
if event.keysym == 'Left':
left = False
if event.keysym == 'Up':
up = False
def task():
if right:
print 'Right'
if left:
print 'Left'
if up:
print 'Forward'
root.after(20,task)
root = tk.Tk()
print( "Press arrow key (Escape key to exit):" )
root.bind_all('<Key>', keyPressed)
root.bind_all('<KeyRelease>', keyReleased)
root.after(20,task)
root.withdraw()
root.mainloop()
The issue began when I started using root.after().
In python, functions create a new scope. If a variable isn’t found within the function’s scope, python looks in the outer (module/file) scope for the variable. You add variables into the current scope with assignment. This all means that:
In order to actually modify the variable in an outer scope, you need to tell python that you want to do something like that explicitly:
This works, but it’s not considered good practice because you’re changing the state of your program. Now the value of
rightdepends on whether you’ve called a function which is a bit unsettling.A better way to share data between function calls is to use a class. Then methods (functions bound to an instance of the class) can change the state of that single instance, but the rest of your program can continue as if nothing happened.
Here’s a slightly more “classy” version of your code: