0

I'm trying to toggle a boolean with the help of a seperate function. If my research is correct, there are no pointers in Python (I'm starting to learn it right now) so I'm unsure how to fix this issue.

For key presses i am using the library 'keyboard' which uses callbacks for hotkeys. Thus i have to somehow pass the toggle as a callback and need a method for toggling it. (If you have a different approach wihich could solve this its also appreciated)

Doing it inside the while loop like the shutdown call doesn't work. because the keyboard library doesn't have a simple method to check for key press or key release so it would be called repeatedly until the key is released.

import keyboard

# Global Variables
running = False

# ------------
#  FUNCTIONS
# ------------

def shutdown():
  print("Tool shutting down!")
  quit()

def toggle(b):
  b = not b

def init():
  running = False
  keyboard.add_hotkey('alt+1', toggle, args=[running])

# ------------
# MAIN PROGRAM
# ------------

init()

while True:
  if keyboard.is_pressed('alt+q'):
    shutdown()

The Variable should be consistent at least in the main program itself (It can be also consistent globally, which was my latest approach that didn't work out) and be toggled once i use my set hotkey.

DJSchaffner
  • 562
  • 7
  • 22
  • Why not just `running = not running` instead of `b = not b`? Also, see [this post](https://stackoverflow.com/questions/534375/passing-values-in-python) for why your code doesn't work. – meowgoesthedog Mar 25 '19 at 13:27

1 Answers1

2

Its just a problem with the scope of variables

Check this

var1 = False

def changeVar(va):
        va = not va

changeVar(var1)

print(var1)

def changeVar2():
        global var1 
        var1 = not var1
changeVar2()
print(var1)

And in your code you need to define toggle as following :

def toggle(b):
   global running
   running = not running
anilkunchalaece
  • 388
  • 2
  • 10