首页 > 解决方案 > 如何在tkinter中按下按钮多次导入另一个python文件?

问题描述

def addstudent():
   import add_student


b1=  Button(root, text="Add Student",width=35,font=("Times New Roman",15),command=addstudent)

b1.place(relx=0.5,rely=0.24,anchor=CENTER)

我试图在按下按钮时多次导入 add_student。当第一次按下按钮时,addstudent 函数会导入 add_student 文件。但是当下次按下按钮时,该功能不会导入 add_student 文件。

标签: pythonpython-3.xtkinter

解决方案


我不确定这会产生什么样的结果,但我认为您希望您调用以add_student产生某种“副作用”(向数据库添加一行,向列表添加一个元素,......)。

确实,有时导入名称会产生副作用,但现在可能就是这种情况。

您很可能必须使用您已导入的名称来调用该函数,例如以下代码。

def addstudent():
    import add_student # make the name add_student visible in the function
    add_student() # call the function and possibly do some work, including side-effects

推荐阅读