2016-03-09 68 views
0

與我在一個單獨的文件中創建的函數有問題。變量顯然沒有被定義,當它是

這裏是我的根程序:

#Import TKINTER toolset: 
from tkinter import * 
from mousexy import * 

#Starting variables: 
#Defining mouse x and y coordinates 

global mouse_x 
global mouse_y 
mouse_x = 0 
mouse_y = 0 

#Main window: 
window = Tk() 
window.title = ("Solomon's animation tool") 

#Workspace and Canvas: 
global wrkspace 
wrkspace = Frame(window, bg="red",width=640,height=480) 
global canvas 
canvas = Canvas(wrkspace,bg="white",width=640,height=480) 

#Keyframe editor: (DO LATER) 

#Test for finding mouse xy 
canvas.bind("<Button-1>",find_mouse_xy) 

wrkspace.pack() 
canvas.pack() 

#Runs window: 
window.mainloop() 

,這裏是我的功能在一個單獨的文件(mousexy.py)

def find_mouse_xy(event): 
    mouse_x = canvas.winfo_pointerx() 
    mouse_y = canvas.winfo_pointery() 
    print ("x: " + str(mouse_x)) 
    print ("y: " + str(mouse_y)) 

當我運行我的根程序,並單擊,控制檯告訴我, canvas沒有定義,當它清楚,我做錯了什麼?

mouse_x = canvas.winfo_pointerx() 
NameError: name 'canvas' is not defined 
Exception in Tkinter callback 
Traceback (most recent call last): 
    File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__ 
    return self.func(*args) 
    File "C:\Users\SOLLUU\Documents\Python\Animation software\mousexy.py", line 2, in find_mouse_xy 
    mouse_x = canvas.winfo_pointerx() 
NameError: name 'canvas' is not defined 
>>> 
+1

請分享錯誤的*完全回溯*。 –

+3

全局變量*爲每個模塊*,'mousexy'不會具有相同的全局變量。 –

+1

最後但並非最不重要的一點是,當Python拋出一個'NameError'異常時,名稱顯然是* not * defined。不在Python正在尋找的地方。 –

回答

1

find_mouse_xy正在尋找mousexy.canvas。你定義了__main__.canvas。它們是兩個完全獨立的變量。

你可能想要的是

def find_mouse_xy(event): 
    # Coordinate of the mouse when the event occurred. 
    mouse_x = event.x 
    mouse_y = event.y 
    # What object was clicked? This handler could 
    # be attached to many different widgets in your program. 
    where = event.widget 
    # ... 
+0

那麼我該如何解決它?對不起,我覺得這很糟糕。 – solluu

+0

這取決於你如何使用'find_mouse_xy'。但是,我懷疑函數需要的信息在傳遞給它的'event'對象中。 – chepner

+0

好的,那麼我如何獲得canvas變量來使用mousexy? – solluu

相關問題