2017-06-29 78 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部分

相關問題