我在Python 3.5中使用Kivy。我正在尝试建立一个应用程序,在该应用程序中,按下按钮即可安排功能调用。一个前提:这是我使用Kivy的第一个应用程序,而我对Python的了解不是很好。这是我的简化代码:
class MyApp(App):
def build(self):
layout = GridLayout(cols=2)
TextStream = Label(text = 'Something will be written here: ')
StartButton = Button(text = 'Start writing')
StartButton.bind(on_press=lambda x:self.start_program(freq=10))
layout.add_widget(TextStream)
layout.add_widget(StartButton)
return layout
def start_program(self, freq):
Clock.schedule_interval(self.write_something, 1.0/freq)
# Also tried Clock.schedule_interval(self.write_something(), 1.0/freq)
def write_something(self):
TextStream.text =+ 'Something '
if __name__ == '__main__':
MyApp().run()
运行脚本时得到的是:
TypeError: write_something() takes 1 positional argument but 2 were given
在阅读关于this question的答案时,我了解到Python中的方法实际上与在代码中的显示方式不同。
更准确地说,从this comment可以理解,正确地声明方法write_something
为参数self
是正确的方法。另外,从this answer中,我得到Python计数的传递参数的数量应为1 + N,其中在调用中传递了N。我没有在电话中传递任何参数。
那么,是否有Kivy传递了一些沉默的论点?我以错误的方式调用该方法吗?
编辑-错误堆栈
如评论所建议,我包括了整个错误堆栈:
Traceback (most recent call last):
File "<ipython-input-1-5d17b5569154>", line 1, in <module>
runfile('/home/raggot/Projects/MyApp/scripts/_test_kivy.py', wdir='/home/raggot/Projects/MyApp/scripts')
File "/usr/local/lib/python3.5/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "/usr/local/lib/python3.5/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/raggot/Projects/MyApp/scripts/_test_kivy_camera.py", line 78, in <module>
MyApp().run()
File "/usr/local/lib/python3.5/dist-packages/kivy/app.py", line 826, in run
runTouchApp()
File "/usr/local/lib/python3.5/dist-packages/kivy/base.py", line 502, in runTouchApp
EventLoop.window.mainloop()
File "/usr/local/lib/python3.5/dist-packages/kivy/core/window/window_pygame.py", line 403, in mainloop
self._mainloop()
File "/usr/local/lib/python3.5/dist-packages/kivy/core/window/window_pygame.py", line 289, in _mainloop
EventLoop.idle()
File "/usr/local/lib/python3.5/dist-packages/kivy/base.py", line 337, in idle
Clock.tick()
File "/usr/local/lib/python3.5/dist-packages/kivy/clock.py", line 581, in tick
self._process_events()
File "kivy/_clock.pyx", line 384, in kivy._clock.CyClockBase._process_events
File "kivy/_clock.pyx", line 414, in kivy._clock.CyClockBase._process_events
File "kivy/_clock.pyx", line 412, in kivy._clock.CyClockBase._process_events
File "kivy/_clock.pyx", line 167, in kivy._clock.ClockEvent.tick
TypeError: write_something() takes 1 positional argument but 2 were given
答案 0 :(得分:1)
当它连接任何事件时,在这种情况下,schedule_interval
Kivy会向其传递其他参数,因此它会向您抛出该错误,在您的情况下,它仅使用args
而您没有任何问题。对于Clock
,它将通过dt
,这是准确的通话时间。
def start_program(self, freq):
Clock.schedule_interval(self.write_something, 1.0/freq)
def write_something(self, *args):
print(args)