0

So i was making an alarm clock with python using tkinter I set up my layout for i wanted it to look, then i decided to implement the plus button in order to increase the number of minutes or hours by which i wanted to set the alarm the alarm clock layout

For some reason, it says that the 'demo_hour' variable has been refered to before the assignment Is there something wrong with the logic in my code?

The needed code:

    demo_hour = 0
    demo_minute = 0
    demo_am_pm = "AM"

    hour = time.strftime("%I")
    minute = time.strftime("%M")
    am_pm = time.strftime("%p")

    mytime.config(text=f"|{demo_hour}| : |{demo_minute}| |{demo_am_pm}|")

    # Up/Down commands
    def u_hr():
        demo_hour += 1
        mytime.config(text=f"|{demo_hour}| : |{demo_minute}| |{demo_am_pm}|")
    def u_m():
        demo_minute += 1
        mytime.config(text=f"|{demo_hour}| : |{demo_minute}| |{demo_am_pm}|")
    def u_ap():
        demo_am_pm = "PM"
        up_hr.config(state=DISABLED)
        mytime.config(text=f"|{demo_hour}| : |{demo_minute}| |{demo_am_pm}|")

    def d_hr():
        demo_hour -= 1
        mytime.config(text=f"|{demo_hour}| : |{demo_minute}| |{demo_am_pm}|")
    def d_m():
        demo_minute -= 1
        mytime.config(text=f"|{demo_hour}| : |{demo_minute}| |{demo_am_pm}|")
    def d_ap():
        demo_am_pm = "AM"
        dw_hr.config(state=DISABLED)
        mytime.config(text=f"|{demo_hour}| : |{demo_minute}| |{demo_am_pm}|")

The needed error:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
    return self.func(*args)
  File "/Users/veresh/Desktop/Python Projects/alarm.py", line 112, in u_hr
    demo_hour += 1
UnboundLocalError: local variable 'demo_hour' referenced before assignment
  • 1
    Use have to use [global](https://www.programiz.com/python-programming/global-keyword) to use local variables in any function. – Saad Apr 10 '21 at 03:05
  • Is `demo_hour` perhaps initialized in an `__init__()` method of a class? And then accessed from another method in the same class? In that case you need to assing it as an object variable, using the `self.demo_hour` notation, everywhere it is used. – JohanL Apr 10 '21 at 05:16

1 Answers1

0

You need to use global as rightly said by @Saad

demo_hour = 0
def u_hr():
    global demo_hour #Use global
    demo_hour += 1
    mytime.config(text=f"|{demo_hour}| : |{demo_minute}| |{demo_am_pm}|")
    #[...] some part of code here
CopyrightC
  • 857
  • 2
  • 7
  • 15