【问题标题】:takes exactly 1 positional argument (0 given)恰好采用 1 个位置参数(给定 0)
【发布时间】:2015-06-06 00:31:50
【问题描述】:

我正在努力做到这一点,所以每次点击按钮时,我都可以运行不同的东西。

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)

【问题讨论】:

  • 那么你在哪里打电话给B_C()
  • 您的意思是让Counter 在您的代码中成为全局变量吗?
  • 我在搞乱 tkinter 并且我有一个 Button 但我希望它在每次点击它时运行不同的东西
  • 然后在您的问题中显示该上下文。理想情况下,请给我们minimal verifiable example 以帮助我们重现您的问题。
  • 注意 Python 区分大小写:Counter 不是 counterPrint 绝对不是 print

标签: python python-3.x typeerror


【解决方案1】:

不要使用全局变量...如果你想修改一个对象,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

这是一个可变对象和通过引用传递的例子(我相信python总是通过引用传递但有可变和不可变对象)。

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

【讨论】:

  • 我还建议您将 class MyCount() 示例用于生产用途,但对于快速和肮脏的、非线程和本地使用的全局变量我认为是好的 :)
【解决方案2】:

试试这个:

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

第一件事:python 区分大小写,所以 Counter 不等于 counter。在函数中你可以使用global counter,这样你就不需要将计数器传递给按钮点击。

【讨论】:

  • 挑衅地使用全局变量不是首选方式。用于本地使用、测试、快速任务,使用没有问题,但是如果您编写一个真正的部署应用程序,您应该避免使用全局变量并将您的计数器放在自己的类中,正如贾斯汀在他的 MyCounter() 类中所建议的那样
猜你喜欢
  • 1970-01-01
  • 2013-05-26
  • 2016-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
相关资源
最近更新 更多