【问题标题】:How to solve this function problem in python [duplicate]如何在python中解决这个函数问题[重复]
【发布时间】:2021-10-14 05:31:54
【问题描述】:

我不知道如何从另一个 python 文件中导入函数并将其放入按钮函数中。这是我亲自编写的代码:

def press_btn1():
    text = entry1.get()
    if text == "something":
        test()
        return None

【问题讨论】:

  • 哦,test() 函数也在另一个文件中(也是 .py)
  • from myotherfile import test 应该这样做。注意:from myotherfile 不是 from myotherfile.py.

标签: python


【解决方案1】:

我假设以下情况:

在文件 also.py 中,你有测试功能:

def test():
 ...
 ...

在您使用 test() 的 main(假设 main.py)中:

import also as a
..
..
..
def press_btn1():
    text = entry1.get()
    if text == "something":
        a.test()
        return None

确保also.py 和 main.py 在同一目录中

如果它们在不同的目录中,则read this

【讨论】:

  • 非常感谢!这是我使用 stackoverflow 的第一天,这很有帮助,谢谢!
【解决方案2】:

假设您有两个 .py 文件 main_file 和 sub_file

所以在 sub_file 中,我有一个名为 print_hello() 的函数,可以打印 hello。

这是在子文件中:

def print_hello():
    print('hello')

因此,要在 main_file 中访问此函数,您必须导入 sub_file 并在 sub_file 中调用该函数:

这是在 main_file 中:

import sub_file

sub_file.print_hello()

所以这将输出为hello

现在你可以在你的代码中使用这个概念

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2012-02-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多