“未定义”的功能参数在Python
调用每当我Tkinter
程序蟒蛇的东西,代码如下所示:“未定义”的功能参数在Python
from Tkinter import *
class GUI():
def __init__(self, master):
self.master = master # master is an instance of Tk
self.master.title("") # set the name of the window
self.frame = Frame(self.master, width=800, height=500, bg="#eeeeee")
# 800, 500 and "#eeeeee" are examples of course
self.frame.pack()
self.canvas = Canvas(self.frame, width=800, height=500, bg="ffffff")
self.canvas.place(x=0, y=0)
#mostly there are some other widgets
# here are obviously other methods
def main():
root = Tk()
app = GUI(root) # root and app.master are synonyms now
app.master.mainloop()
if __name__ == '__main__':
main()
我的问题是,我真的不明白,为什么Frame(width=800, height=500)
或place(x=0, y=0)
工作:我没有定义参数height
,width
,x
和y
。查看模块Tkinter
中的代码,函数需要一个名为*args
或**kw
的参数。我知道如何使用它们(至少足够开发一些小应用程序),但我不知道如何定义一个使用这个参数的函数。我觉得我对python的这一部分并不十分了解,尽管我可以使用它。
所以我的问题是:
我怎么可以定义一个函数,所谓的语法如下:
functionName(parameterName1 = value, paramterName2 = value, ...)
我并不需要知道如何使一个功能是什么接受变参数的数量(与我的问题相结合),但它也可以。
你所指的是关键字参数。
可以说,用特定关键字参数定义函数的最好方法之一是提供默认值。这是常见的默认为None
,如果你没有任何其他默认的需要:
def functionName(parameterName1=None, parameterName2=None):
print("parameter one is: %s" % str(parameterName1))
print("parameter two is: %s" % str(parameterName2))
然后,您可以调用这个函数像这样:
foo = functionName(parameterName1="hello", parameterName2="world")
您还可以做什么的Tkinter函数做,并接受**kwargs
作为参数。这会收集所有已命名的参数到一个字典,然后可以遍历:
def functionName(**kwargs):
print("the arguments are:", kwargs)
注意:您不必使用名称kwargs
- 你可以使用任何你想要的名称(**kw
,**kwargs
,**whatever
),但kwargs
似乎是最常见的。
谢谢,我已经知道如何设置默认值,我只是不知道我可以在函数调用中键入参数名称。 – Aemyl
任何基本的python教程都会告诉你如何做到这一点。这是标准教程中的[定义函数](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)。 – tdelaney