我有一个基本的问题,但我不知道如何解决它。你知道吗
我正在制作一个程序,让用户在画布上画线。我以前在一个文件中有完整的代码,但由于我要添加许多新工具,所以将所有函数隔离到单独的文件中似乎是一个明智的决定。 然而,这样做却产生了问题。抱歉,有很多代码需要通过。这是我的密码:
根程序:根.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()
这个文件定义了从一开始就需要的所有变量_变量.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)
出于某种原因,当我运行根程序时,在根.py控制面板尚未定义,但我运行了定义它的函数。我做错什么了?你知道吗
您需要理解python中的作用域。在
start_vars
函数中所做的一切对程序的其余部分都是无用的。control_panel
只存在于函数体中。当函数完成时,您没有control_panel
虽然这是一个糟糕的编程开始,你可以尝试这样做:
然后,在你的
root.py
中,在某个时刻这样做然后你就可以得到你的
control_panel
了根.py像这样只有在这之后,才能使用
control_panel
变量。你知道吗此外,你可以做这样的黑客
但这是一个错误的建议,你的程序结构不好。你知道吗
[编辑] 既然你看起来有点困惑,我会这样做:
这可以在
starting_variables.py
模块中 然后,在root.py
中,您可以我不确定你是否熟悉面向对象,但这正是我应该做的。您的方法完全可以在C中使用,但是Python没有您所期望的全局变量。。。。一切都是一个模块的属性,一个对象……什么的。你知道吗
我之所以认为我编写代码的方式更好,是因为在Python中,触摸像
locals
、globals
这样的函数或触摸其他模块的模块属性被认为是不好的,因为这是出乎意料的。人们期望函数返回值,对象保存属性和方法,类描述对象等等。。。抱歉,如果我用太多的理论让你厌烦了,伙计,希望解释能帮上忙:)相关问题 更多 >
编程相关推荐