2017-06-29 25 views
-7

“CmdBtn ['menu'] = CmdBtn.menu”在第二行最后一行是什么意思。什么是字符串在数组中的含义python

def makeCommandMenu(): 
    CmdBtn = Menubutton(mBar, text='Button Commands', underline=0) 
    CmdBtn.pack(side=LEFT, padx="2m") 
    CmdBtn.menu = Menu(CmdBtn) 
    ... 
    ... 
    CmdBtn['menu'] = CmdBtn.menu 
    return CmdBtn 
+2

这意味着['CmdButton .__ setitem __('menu',CmdBtn.menu)'](http://epydoc.sourceforge.net/stdlib/Tkinter.Misc -class.html #__setitem__),这显然是为给定的键设置资源值。 – khelwood

+0

欢迎来到计算器。你的问题可能因为两个原因而被大量降低:1.它没有为你的问题提供上下文,以及2.它询问了python非常非常基本的部分(括号[]'运算符)的含义,这意味着你可能没有打算阅读教程,或者你在问“MenuButton”对象的“菜单”键的具体含义。如果最后一种情况是这样,你需要在你的问题上更加明确(见点#1)。如果它是第一个,那么它将有助于更清楚地知道你到底在问什么。 –

回答

0

当您使用x[y] = z,它会调用__setitem__方法。

x.__setitem__(y, z) 

在你的情况,CmdBtn['menu'] = CmdBtn.menu意味着

CmdBtn.__setitem__('menu', CmdBtn.menu) 

Menubutton类确实提供了一个__setitem__ method。它看起来像用于为给定密钥('menu')设置“资源值”(在此例中为CmdBtn.menu)。

0

这不是“数组内的字符串”。

托架操作员用于在某种序列的(通常是listtuple)项的访问,映射(通常是dict,或字典),或一些其他类型的特殊对象的(如本MenuButton对象,这不是一个序列或映射)。与其他一些语言不同的是,在python中,任何对象都可以使用这个运算符。

A list与其他语言的“数组”类似。它可以包含任何类型的对象的混合体,并且它维护对象的顺序。 A list对象对于何时要维护对象的有序序列非常有用。您可以使用它的索引访问一个list的对象,像这样(索引从0开始):

x = [1,2,3] # this is a list 
assert x[0] == 1 # access the first item in the list 
x = list(range(1,4)) # another way to make the same list 

一个dict(字典)是当你想这样你就可以查找到的值与键关联有用稍后使用键的值。像这样:

d = dict(a=1, b=2, c=3) # this is a dict 
assert x['a'] == 1 # access the dict 
d = {'a':1, 'b':2, 'c':3} # another way to make the same dict 

最后,您可能还会遇到也使用相同项目访问接口的自定义对象。在Menubutton的情况下,['menu']只是访问响应密钥'menu'的某个项目(由tkinter API定义)。你可以让你自己的对象类型和项的访问,太(Python 3中下面的代码):

class MyObject: 
    def __getitem__(self, x): 
     return "Here I am!" 

这个对象没有做太多,除了返回相同的字符串键或索引值,你给它:

obj = MyObject() 
print(obj [100]) # Here I am! 
print(obj [101]) # Here I am! 
print(obj ['Anything']) # Here I am! 
print(obj ['foo bar baz']) # Here I am! 
0

首先,在Python everything is an object和方括号表示该对象是标化的(对于例如tuplelistdictstring以及更多)。可下注意味着此对象至少实现了__getitem__()方法(在您的情况下为__setitem__())。

使用这些方法很容易与类成员进行交互,因此不要害怕构建自己的示例,了解其他人的代码。

尝试这个片段:

class FooBar: 
    def __init__(self): 
     # just two simple members 
     self.foo = 'foo' 
     self.bar = 'bar' 

    def __getitem__(self, item): 
     # example getitem function 
     return self.__dict__[item] 

    def __setitem__(self, key, value): 
     # example setitem function 
     self.__dict__[key] = value 

# create an instance of FooBar 
fb = FooBar() 

# lets print members of instance 
# also try to comment out get and set functions to see the difference 
print(fb['foo'], fb['bar']) 

# lets try to change member via __setitem__ 
fb['foo'] = 'baz' 

# lets print members of instance again to see the difference 
print(fb['foo'], fb['bar']) 
0

它是简写CmdBtn.configure(menu=CmdBtn.menu)

设置插件选项的方式通常在创建时(例如:Menubutton(..., menu=...))或使用configure方法(例如:CmdBtn.configure(menu=...)。 Tkinter提供了第三种方法,将小部件当作字典处理,其中配置值是字典的关键字(例如:CMdBtn['menu']=...

这包括在官方python tkinter文档的Setting Options部分

相关问题