简体   繁体   English

在 tkinter 中按下按钮时导入新的 python 文件

[英]Importing a new python file when a button is pressed in tkinter

I need to load up a quiz that is in a separate python file when a button is pressed in one of the menus.当在其中一个菜单中按下按钮时,我需要加载一个单独的 python 文件中的测验。 I tried to use import, however it causes the other python file to run straight away, rather than only when the button is pressed, how would I fix this?我尝试使用导入,但是它会导致另一个 python 文件立即运行,而不仅仅是在按下按钮时,我该如何解决这个问题?

import FSMQuiz1

def selectTask():
            screen7 = Toplevel(screen5)
            screen7.geometry("600x450+686+254")
            screen7.title("Select a task")
            Label(screen7, text = "Please select a task...", font = ("Calbiri",14)).place(relx=0.25, rely=0.044, height=41, width=304)
            Button(screen7, text = "Finite State Machines", command = FSMQuiz1).place(relx=0.15, rely=0.2, height=54, width=117)

what if you use the python build in function exec?如果你在函数exec中使用python构建怎么办?

you can use this function to load a file:您可以使用此函数加载文件:

def exec_file(file_name):
    #open the file
    with open('your/file.txt') as fh:
        #read it
        data = fh.read()
    #execute it
    exec(data)

You can use importlib to load python files.您可以使用 importlib 加载 python 文件。

from os import path
from importlib.util import module_from_spec, spec_from_file_location

spec = spec_from_file_location("module.name", path.join(PATH, 'file.py'))
module = module_from_spec(spec)
spec.loader.exec_module(module)

Try:尝试:

import FSMQuiz1

def selectTask():
            screen7 = Toplevel(screen5)
            screen7.geometry("600x450+686+254")
            screen7.title("Select a task")
            Label(screen7, text = "Please select a task...", font = ("Calbiri",14)).place(relx=0.25, rely=0.044, height=41, width=304)
            Button(screen7, text = "Finite State Machines", command = lambda: FSMQuiz1).place(relx=0.15, rely=0.2, height=54, width=117)

Set the button command in a define, then use the command to call it, eample:在定义中设置按钮命令,然后使用命令调用它,例如:

def CallButton():
    import FSMQuiz1
def selectTask():
            screen7 = Toplevel(screen5)
            screen7.geometry("600x450+686+254")
            screen7.title("Select a task")
            Label(screen7, text = "Please select a task...", font = ("Calbiri",14)).place(relx=0.25, rely=0.044, height=41, width=304)
            Button(screen7, text = "Finite State Machines", command = CallButton).place(relx=0.15, rely=0.2, height=54, width=117)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM