我有一个创建一些标签和输入字段的函数,还有一个按钮。我想要按钮的命令函数从这个函数管理对象。我可以在不使变量为全局变量的情况下执行此操作吗
代码如下:
def add_clicked():
cuspsInfo.append((int(xInput.get()), int(yInput.get()), indexInput.get()))
xInput.delete(0, END)
yInput.delete(0, END)
indexInput.delete(0, END)
def startup_menu():
global cuspsInfo
cuspsInfo = []
global label
label = Label(window, text="Add a cusp:", font=("Arial", 20, "bold"),
fg=SECOND_COLOR, bg=FIRST_COLOR)
label.place(relx=0.5, rely=0.3, anchor=CENTER)
global xInput
global yInput
global indexInput
xInput = Entry(window)
xInput.place(relx=0.52, rely=0.4, anchor=CENTER)
yInput = Entry(window)
yInput.place(relx=0.52, rely=0.45, anchor=CENTER)
indexInput = Entry(window)
indexInput.place(relx=0.52, rely=0.5, anchor=CENTER)
global xLabel
global yLabel
global indexLabel
xLabel = Label(window, text="x(0-500):", font=(
"Arial", 20, "bold"), fg=SECOND_COLOR, bg=FIRST_COLOR)
xLabel.place(relx=0.34, rely=0.4, anchor=CENTER)
yLabel = Label(window, text="y(0-500):", font=(
"Arial", 20, "bold"), fg=SECOND_COLOR, bg=FIRST_COLOR)
yLabel.place(relx=0.34, rely=0.45, anchor=CENTER)
indexLabel = Label(window, text="name:", font=(
"Arial", 20, "bold"), fg=SECOND_COLOR, bg=FIRST_COLOR)
indexLabel.place(relx=0.36, rely=0.5, anchor=CENTER)
global addButton
global runButton
addButton = Button(window, text="add", command=add_clicked)
addButton.place(relx=0.45, rely=0.6, anchor=CENTER)
runButton = Button(window, text="run", command=run_clicked)
runButton.place(relx=0.55, rely=0.6, anchor=CENTER)
我会“部分应用”这个函数。首先,将回调更改为接受四个参数:
现在,将对该回调的调用包装到另一个函数中,然后提供参数。这可以通过一个简单的
lambda
实现:或与
functools.partial
一起:这两种方法都有相同的效果:参数是“预先提供的”,以便以后可以在没有任何参数的情况下调用回调
正如你所看到的,随着争论的增加,这变得越来越混乱。这种技术最适合于数量较少的参数。如果有很多数据需要传递到函数中,那么将它们放入
NamedTuple
或完整的自定义类中(如果它们非常相似并且在一起有意义的话)可能是有意义的相关问题 更多 >
编程相关推荐