【问题标题】:How to run python file inside another python file如何在另一个python文件中运行python文件
【发布时间】:2020-07-08 19:47:55
【问题描述】:

如何让这个包含 kivy 的 python 代码在另一个包含 kivy 的 python 代码中运行,就像你会调用一个函数一样,这样我就可以拥有不同的代码段。我不希望在特定的 python 文件上有太多代码,因为我会处理大代码。

import kivy
from kivy.app import App
from kivy.uix.floatlayout import Floatlayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.label import Label 


class LandingScreen(FloatLayout):
    def __init__(self, **kwargs):
        super(LandingScreen, self).__init__(**kwargs)

         
        self.btn1=Button(text='button1 ', size_hint=(0.5, 0.5), 
        on_press=self.click_b1))
        self.btn2=Button(text='button2', size_hint=(0.5, 0.5), 
        on_press=self.click_b2))


            
        self.add_widget(self.btn1)
        self.add_widget(self.btn2)

        def click_b1(self, instance):
             
             pass
        def click_b2(self, instance):
             pass
       
class SplashApp(App):
    def build(self):
        return LandingScreen()

if __name__ == '__main__':
    SplashApp().run()

假设第一个文件是a.py,第二个文件是b.py,我如何在下面的另一个python文件中调用这个python文件

import kivy
from kivy.app import App
from kivy.uix.floatlayout import Floatlayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.label import Label 


class LandingScreen2(FloatLayout):
    def __init__(self, **kwargs):
        super(LandingScreen2, self).__init__(**kwargs)

         
        self.btn3=Button(text='button1 ', size_hint=(0.5, 0.5), 
        on_press=self.click_b3))
        self.btn4=Button(text='button2', size_hint=(0.5, 0.5), 
        on_press=self.click_b4))


            
        self.add_widget(self.btn3)
        self.add_widget(self.btn4)

        def click_b3(self, instance):
             
             pass
        def click_b4(self, instance):
             pass
       
class SplashApp(App):
    def build(self):
        return LandingScreen2()

if __name__ == '__main__':
    SplashApp().run()

【问题讨论】:

标签: python kivy kivy-language


【解决方案1】:

要调用另一个文件,你把它当作一个模块,你会使用:

#a.py
import b
b.execute()
#b.py
def execute() :
    print("This works!")

所有变量和函数都需要前缀 b. 才能引用示例中的“模块”

此问题可能与以下问题重复:

https://stackoverflow.com/questions/2349991/how-to-import-other-python-files

【讨论】:

    【解决方案2】:

    它叫import。您可以在当前模块中导入第二个模块,例如 b.py 并调用该模块的入口点。

    a.py

    import b
    ...
    ...
    #call b.py entry point.
    b.SplashApp().run()
    

    你可以做一些更普通的事情,产生一个新的进程,并通过 shell 用 python 调用 b.py(但这很特别,我提到这个只是为了让你知道你可以用 python 做任何你喜欢的事情)

    import subprocess
    p= subprocess.Popen("python b.py",shell=True)
    p.communicate
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-06
      • 2013-02-24
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 2021-04-17
      相关资源
      最近更新 更多