简体   繁体   中英

what does this Unresolved reference mean?

I am trying to count mouse clicks, by incrementing a variable in python.

from tkinter import *
import serial, time
root = Tk()

ser = serial.Serial()
ser.baudrate=9600
ser.port=0

x = 0
def leftClix(event):
    print("Left")
    if x == 3:
        exit(0)
    else:
        x=x+1
def rightClix(event):
    print("Right")

def middleClix(event):
    print("Middle")

frame = Frame(root, width=300, height=250)
frame.bind("<Button-1>", leftClix)
frame.bind("<Button-2>", middleClix)
frame.bind("<Button-3>", rightClix)
frame.pack()

root.mainloop()

in PyCharm, "x" in x+1 is underlined with a note: unresolved reference:

when I click the left mouse button, I get "UnboundLocalError: local variable 'x' referenced before assignment"

What does that mean? I assigned it before... so I don't understand. I tried making xa global, but that did not help. Can someone explain what I'm doing wrong here?

As @khelwood said, mark x as global like this:

def leftClix(event):
  global x
  ...
  x = x + 1

This appears in the Python Programming FAQ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM