【问题标题】:How can I use Python modules without having to explicitly import them? [duplicate]如何使用 Python 模块而无需显式导入它们? [复制]
【发布时间】:2021-12-19 15:52:21
【问题描述】:

我正在尝试为我的程序导入模块。在这段代码中,我收到了所有文件,但是当我尝试导入变量时,它返回错误。

我不想在代码中对导入进行硬编码,我希望能够添加新的 python 文件而无需手动将它们添加到代码中。请参阅loadCommandFiles() 函数以了解我的尝试。

主文件:

import tkinter as tk
import os

def main():
    global main_entry
    main_entry = tk.Entry(font = ("Helvetica", 30, "bold"))
    main_entry.pack()
    main_entry.focus_set()
    main_entry.bind('<Return>', entry_parser)

def entry_parser(dontCare):
    entry_string = main_entry.get()

def loadCommandFiles():
    for file in os.listdir(os.getcwd()):
        if file.endswith(".py"):
            if file.endswith("jarvis.py") == False:
                exec("import {}".format(file.replace(".py", "")))
                print(basicCommands.commands)
                
terminal = tk.Tk()
terminal.overrideredirect(True)

terminal.geometry("+{}+{}".format(int(terminal.winfo_screenwidth()/2 - terminal.winfo_reqwidth()/2), int(terminal.winfo_screenheight()/2 - terminal.winfo_reqheight()/2)))

loadCommandFiles()

main()

terminal.mainloop()

basicCommands.py

commands = ["schnitzel"]

错误:

NameError: name 'basicCommands' 未定义

【问题讨论】:

  • 你必须在主文件中import basicCommands
  • 但是您甚至没有导入basicCommands,为什么您认为可以在其中使用变量而不导入它?您提到您正在导入另一个文件,但没有 import basicCommands
  • @Gary02127 是的,但我希望能够添加 python 文件而不在主代码中硬编码它们。
  • @thekingoflorda 那么你希望它如何工作?您只想自动导入同一目录中的每个 .py 文件吗?这可能与代码有关,但您没有在帖子中指定所有内容。
  • @RandomDavis 是的,我确实是这个意思。我已经更改了文本以更好地解释这一点。

标签: python file tkinter


【解决方案1】:

启动你的主程序:

import tkinter as tk
import os
import basicCommands

如果您想以编程方式导入,请尝试更改行:

            exec("_import '{}'".format(file.replace(".py", "")))

到:

            __import__(file.replace(".py", ""))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    相关资源
    最近更新 更多