2015-04-01 75 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

相關問題