2013-09-30 63 views
2

我是初學者使用Tkinter模塊的一些非常基本的GUI編程。 我試着運行該程序,我從其他網頁複製的源代碼。以下程序如何運行?

from Tkinter import * 

    def sel(): 
     selection = "You selected the option " + str(var.get()) 
     label.config(text = selection) 

    root = Tk() 
    var = IntVar() 
    R1 = Radiobutton(root, text="Option 1", variable=var, value=1, 
       command=sel) 
    R1.pack(anchor = W) 

    R2 = Radiobutton(root, text="Option 2", variable=var, value=2, 
       command=sel) 
    R2.pack(anchor = W) 

    R3 = Radiobutton(root, text="Option 3", variable=var, value=3, 
       command=sel) 
    R3.pack(anchor = W) 

    label = Label(root) 
    label.pack() 
    root.mainloop() 

我的疑問是,當我們訪問函數中的全局對象,我們必須寫

global object_name 

,然後功能工作正常,否則該功能使得自己的局部變量的副本。那麼爲什麼我們不在函數sel()的定義中做同樣的事情?我嘗試將以下語句添加到sel()的定義中?此外,

global label 
    global var 

並運行該程序,但它沒有區別於該程序的工作。這是爲什麼?

+1

當*修改*全局變量時,您只需要'global'。 – That1Guy

回答

2

修改全局變量時,您只需要global

請看下面的例子:

myglobal = 'myglobal' 

def test_global(): 
    print myglobal 

test_global() 

myglobal #output 

如果我們看一看,我們看到變量myglobal加載爲一個全球性的字節碼:

import dis 

dis.dis(test_global) 

    2   0 LOAD_GLOBAL    0 (myglobal) 
       3 PRINT_ITEM 
       4 PRINT_NEWLINE 
       5 LOAD_CONST    0 (None) 
       8 RETURN_VALUE 

但是,如果我們定義myglobal我們看到myglobal作爲常量或局部變量加載。

import dis 

def test_global(): 
    myglobal = 'mylocal' 

dis.dis(test_global) 

    2   0 LOAD_CONST    1 ('mylocal') 
       3 STORE_FAST    0 (myglobal) 
       6 LOAD_CONST    0 (None) 
       9 RETURN_VALUE 

如果我們不是試圖修改myglobal VS簡單地定義它:

myglobal += 'another string' 

我們得到UnboundLocalError,因爲我們還沒有告訴Python中的變量myglobal是一個全球性的。試試這樣:

global myglobal 
myglobal += 'another string' 

這將工作得很好。