2015-01-07 62 views
0

我最近問了另一個問題,詢問如何將列表從一個函數傳遞到另一個函數,這由@Modred好心回答。基本上我現在已經得到是這樣的:函數之間的共享列表

def run_command(): 
    machines_off = [] 
     # Some stuff ..... 
     machines_off.append(machineName) 
     # Some stuff .... 
    wol_machines(machines_off) 

def wol_machines(machines_off): 
    # Some stuff .... 

(我已經清除了所有非必要的代碼,在這個例子中,因爲它是300條+線)。

現在,通過點擊tkinter按鈕調用每個函數; run_command始終運行,有時會將項添加到列表'machines_off'。如果單擊第二個功能按鈕,我只想讓它執行machines_off。在點擊run_command按鈕之後,它會遍歷整個腳本,包括第二個功能,當我不需要它時。我假設當我將列表轉發到第二個函數(第五行)時,它忽略了單擊第二個函數按鈕的需要。

我需要更改/添加以允許第一個函數中的列表可用於第二個函數,但在需要之前不執行操作?

非常感謝, 克里斯。

回答

0

我猜你的代碼看起來是這樣的:

from Tkinter import Tk, Button 

def run_command(): 
    machines_off = [] 
    # Some stuff ..... 
    machineName = "foo" 
    machines_off.append(machineName) 
    # Some stuff .... 
    wol_machines(machines_off) 

def wol_machines(machines_off): 
    print "wol_machines was called" 
    print "contents of machines_off: ", machines_off 
    # Some stuff .... 

root = Tk() 
a = Button(text="do the first thing", command=run_command) 
b = Button(text="do the second thing", command=wol_machines) 
a.pack() 
b.pack() 

root.mainloop() 

如果你想要的功能來執行彼此獨立的,你不應該從run_command中調用wol_machines。您必須找到其他方法才能看到該列表。這樣做的一種方法是使用全局值。

from Tkinter import Tk, Button 

machines_off = [] 

def run_command(): 
    #reset machines_off to the empty list. 
    #delete these next two lines if you want to retain old values. 
    global machines_off 
    machines_off = [] 
    # Some stuff ..... 
    machineName = "foo" 
    machines_off.append(machineName) 
    # Some stuff .... 

def wol_machines(): 
    print "wol_machines was called" 
    print "contents of machines_off: ", machines_off 
    # Some stuff .... 

root = Tk() 
a = Button(text="do the first thing", command=run_command) 
b = Button(text="do the second thing", command=wol_machines) 
a.pack() 
b.pack() 

root.mainloop() 

這是你的原代碼,可以給你你想要的行爲,最簡單的變化,但全球值一般認爲是不好的設計的徵兆。更多面向對象的方法可以將全局局部化爲類屬性。

from Tkinter import Tk, Button 

class App(Tk): 
    def __init__(self): 
     Tk.__init__(self) 
     self.machines_off = [] 
     a = Button(self, text="do the first thing", command=self.run_command) 
     b = Button(self, text="do the second thing", command=self.wol_machines) 
     a.pack() 
     b.pack() 
    def run_command(self): 
     #reset machines_off to the empty list. 
     #delete this next line if you want to retain old values. 
     self.machines_off = [] 
     # Some stuff ..... 
     machineName = "foo" 
     self.machines_off.append(machineName) 
     # Some stuff .... 

    def wol_machines(self): 
     print "wol_machines was called" 
     print "contents of machines_off: ", self.machines_off 
     # Some stuff .... 

root = App() 
root.mainloop() 
+0

你是超級巨星!這正是我需要的。 我已經走了第一個選項,因爲它是最簡單易懂的。 雖然有一個問題,爲什麼我不需要第二個函數中的另一個'global machines_off'行? – user3514446