【问题标题】:Error calling function with multiple arguments located in another python file使用位于另一个 python 文件中的多个参数调用函数时出错
【发布时间】:2019-06-08 10:19:08
【问题描述】:

按下按钮时,尝试调用具有三个参数的函数时,程序会中断,但调用不带参数的函数会正确执行。

main.py

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label

from another import Another
class MainWindow(Screen, Another):
    """ This class imports class Another from another.py file"""
    pass


class SecondWindow(Screen, Another):
    """ This class imports class Another from another.py file"""
    pass


class WindowManager(ScreenManager):
    """ This class is to control screen operations."""
    pass


kv = Builder.load_file("my.kv")
class MyMainApp(App):
    def build(self):
        return kv

if __name__ == "__main__":
    MyMainApp().run()

另一个.py

class Another:

    def dummy_one(self):
        print("This is Alpha. This function has zero arguments")

    def dummy_two(self,one, two, three):
        """Just a test function"""
        print('This is:',one)
        print('This is:',two)
        print('This is:',three)
        print('This function has three positional arguments')

obj = Another()
obj.dummy_two('Beta','Gamma','Delta')

我的.kv

WindowManager:
    MainWindow:
    SecondWindow:

<MainWindow>:
    name: "main"
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Welcome to the MAIN SCREEN"
        Button:
            text: "Press Me, See the console output!!!"
            on_release:
                app.root.current = "second"
            on_press:
                root.dummy_one() # This executes fine, has zero arguments


<SecondWindow>:
    name: "second"
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Welcome to the SECOND SCREEN"
        Button:
            text: "Press Me, See the console output. Go back home!!!"
            on_release:
                app.root.current = "main"
                root.manager.transition.direction = "right"
            on_press:
                root.dummy_two()  # This throws error, has three positional arguments

在第二个屏幕中按下按钮时出错: TypeError: dummy_two() 缺少 3 个必需的位置参数:“一”、“二”和“三”

函数 dummy_two(self,one,two,three) 在运行文件 another.py 时正确执行,但在从主文件 (main.py) 调用时崩溃。

【问题讨论】:

  • 我很困惑,root.dummy_two() 有 0 个位置参数(你什么也没传递),你有没有把哪个错误和哪个没有?

标签: python-3.x kivy


【解决方案1】:

None 作为默认值添加到参数中。默认值表示函数参数将采用该值,None 如果在函数调用期间没有传递任何参数值。

片段

def dummy_two(self,one=None, two=None, three=None):

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 2017-11-04
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多