【发布时间】:2016-03-13 15:59:49
【问题描述】:
我遇到了一个看似基本的问题,但我不知道如何解决它。
我正在制作一个程序,让用户在画布上画线。我以前将整个代码放在一个文件中,但由于我要添加许多新工具,因此将所有函数隔离到单独的文件中似乎是一个明智的决定。 然而,这样做会导致问题。很抱歉有很多代码需要通过。这是我的代码:
根程序:root.py(我实际运行的那个)
#Import TKINTER toolset:
from tkinter import *
import starting_variables
#Starting variables:
starting_variables.start_vars()
#Tool width control:
global tool_width
tool_width = Scale(control_panel,from_=1,to=32)
canvas.bind("<Button-1>",line_start_xy)
control_panel.pack(side=LEFT,fill=Y)
tool_width.pack()
wrkspace.pack()
canvas.pack()
#Runs window:
window.mainloop()
这个文件从一开始就定义了所有需要的变量:(starting_variables.py)
from tkinter import *
def start_vars():
#Starting variables:
line_startx = 0
line_starty = 0
line_endx = 0
line_endy = 0
mouse_x = 0
mouse_y = 0
#Main window:
window = Tk()
#Workspace and Canvas:
wrkspace = Frame(window, bg="blue",width=640,height=480)
canvas = Canvas(wrkspace,bg="white",width=640,height=480)
control_panel = Frame(wrkspace,bg="white",width=32,relief=SUNKEN,bd=5)
由于某种原因,当我运行 root 程序时,它告诉我在 root.py 的第 10 行 control_panel 尚未定义,但我运行了定义它的函数。我在这里做错了什么?
【问题讨论】:
-
当您在函数定义中声明这些变量时,它们在此类函数之外不存在。要么在定义中将每个函数声明为
global,要么完全删除带有def的行,然后在root.py 中直接以starting_variables.tool_width访问每个变量。 -
...或者您将
return control_panel添加到def start_vars()的末尾,从而保留您的功能但避免使用globals(通常应该尽可能避免使用它们)。然后你可以在root.py中写ctrl_pnl = starting_variables.start_vars()和ctrl_pnl.pack(side=LEFT,fill=Y)
标签: python tkinter python-3.4