如何从另一个python文件运行文件

时间:2017-11-04 13:07:31

标签: python python-2.7 kivy kivy-language

a.py

from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.lang import Builder


class CustDrop(DropDown):
    def __init__(self, **kwargs):
        super(CustDrop, self).__init__( **kwargs)
        self.select('')


kv_str = Builder.load_string('''


BoxLayout:
    orientation: 'vertical'
    BoxLayout:
        canvas.before:
            Rectangle:
                pos: self.pos
                size: self.size
            Color:
                rgb: (1,1,1)
        size_hint_y:1

        Button:
            id: btn
            text: 'test'
            on_release: dropdown.open(self)
            #size_hint_y: None
            #height: '48dp'  


        CustDrop:

            id: dropdown

            Button:
                text: 'Run another script'
                size_hint_y: None
                height: '48dp'

        Label:
            size_hint_x: 4

    Label:
        size_hint_y: 9

''')


class ExampleApp(App):
    def build(self):
        return kv_str

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

b.py

import kivy
kivy.require('1.0.6') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.label import Label


class MyApp(App):

    def build(self):
        return Label(text='Hello world')


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

当我运行a.py文件后,我点击测试然后下拉显示'运行另一个脚本'。当我点击'运行另一个脚本'(测试子菜单)然后如何运行b.py(MyApp( ).run())。应该在新窗口中打印'Hello world'。

2 个答案:

答案 0 :(得分:1)

解决方案如下:

片段

a.py

...

kv_str = Builder.load_string('''
#:import os os
...
        CustDrop:

            id: dropdown

            Button:
                text: 'Run another script'
                size_hint_y: None
                height: '48dp'
                on_release: os.system("python3 b.py")

输出

enter image description here enter image description here

答案 1 :(得分:1)

而不是调用系统,有一个python模块来做

https://docs.python.org/3/library/runpy.html