显然没有定义变量

2024-10-05 10:18:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个单独的文件中创建了一个函数。在

下面是我的根程序:

#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)在

^{pr2}$

当我运行根程序并单击时,控制台会告诉我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
>>>

Tags: 文件函数infrompyimport程序tkinter
1条回答
网友
1楼 · 发布于 2024-10-05 10:18:35

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
    # ...

相关问题 更多 >

    热门问题