不要使用全局變量...如果你想修改一個對象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
那麼你在哪裏調用'B_C()'? – 2015-04-01 11:24:14
你的意思是讓'Counter'在你的代碼中成爲全局嗎? – 2015-04-01 11:24:45
我搞砸了tkinter,我有一個按鈕但我希望它每次點擊它都能運行不同的東西 – Jayde 2015-04-01 11:26:29