2015-01-07 56 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