2015-04-01 70 views
-6

我试图让它每次点击按钮时都可以运行不同的东西。需要1个位置参数(0给出)

Counter = 0 

def B_C(Counter): 
    Counter = Counter + 1 
    if counter == 1: 
     print("1") 
    elif counter == 2: 
     print("2") 
    else: 
     if counter == 3: 
      Print("3") 

,但我得到

TypeError: B_C() takes exactly 1 positional argument (0 given) 
+0

那么你在哪里调用'B_C()'? – 2015-04-01 11:24:14

+0

你的意思是让'Counter'在你的代码中成为全局吗? – 2015-04-01 11:24:45

+0

我搞砸了tkinter,我有一个按钮但我希望它每次点击它都能运行不同的东西 – Jayde 2015-04-01 11:26:29

回答

3

试试这个:

counter = 0 

def B_C(): 
    global counter 
    counter += 1 
    if counter == 1: 
     print("1") 
    elif counter == 2: 
     print("2") 
    else: 
     if counter == 3: 
      print("3") 

B_C() 
B_C() 
B_C() 

输出:

1 
2 
3 

第一件事:蟒蛇是大小写敏感的,所以计数器不等于计数器。在该功能中,您可以使用global counter,因此您不需要传递按钮点击。

+0

使用全局变量并不是首选方式。对于本地使用,测试,快速任务,没有问题的使用,但如果你写一个真正的应用程序部署,你应该避免使用全局变量,并将你的计数器放在自己的类中,正如Justin用他的'MyCounter()'类 – 2015-04-01 13:34:20

2

不要使用全局变量...如果你想修改一个对象python有可变对象。这些是通过引用传递的结构,并且该函数将在各处改变结构内的值。

下面是一个传值的基本示例,其中函数范围之外的值不会更改。变量“c”下面是一个不可变对象,c的值不会从函数改变。 Immutable vs Mutable types

c = 0 
def foo(c): 
    c = c + 1 
    return c 

m = foo(c) 
print(c) # 0 
print(m) # 1 

这里是一个可变对象的示例,并且通过引用(I相信蟒总是不通过引用传递但具有可变的和不可变的对象)通过。

c = [0] 
def foo(c): 
    c[0] = c[0] + 1 
    return c 

m = foo(c) 
print(c) # [1] 
print(m) # [1] 

或上课。除了全局变量之外。

class MyCount(object): 
    def __init__(self): 
     self.x = 0 
    # end Constructor 

    def B_C(self): 
     self.x += 1 
     pass # do stuff 
    # end B_C 

    def __str__(self): 
     return str(self.x) 
    # end str 
# end class MyCount 

c = MyCount() 
c.B_C() 
print(c) 
c.B_C() 
print(c) 

另外你提到你正在使用一个按钮。如果你想按一个按钮来传递参数到函数中,你可能必须使用lambda函数。我不太了解TKinter,但是对于PySide,您可以通过点击按钮来调用函数。可能没有简单的方法将变量传递给按钮点击功能。 http://www.tutorialspoint.com/python/tk_button.htm

def helloCallBack(txt): 
    tkMessageBox.showinfo("Hello Python", txt) 

# from the link above 
B = Tkinter.Button(top, text="Hello", command= lambda x="Hello": helloCallBack(x)) 
# lambda is actually a function definition. 
# The lambda is like helloCallBack without the parentheses. 
# This helps you pass a variable into a function without much code 
+0

也建议你的'类MyCount()'样本用于生产用途,但对于快速和肮脏的,非线程和本地使用全局都很好,我认为:) – 2015-04-01 13:36:06

相关问题