gpt4 book ai didi

python - 使用 tkinter 时 import stament 的问题

转载 作者:行者123 更新时间:2023-12-04 03:30:11 26 4
gpt4 key购买 nike

我有以下问题:我想将变量从一个文件导入到另一个文件。但是当我从中导入的文件有一个 tkinter 窗口时,它会打开整个窗口,而不仅仅是导入变量。我该如何解决这个问题?

来自 file1 的代码

from tkinter import *

root = Tk()

A = "This is "
B = "a test."
C = A+B
D = Label(root, text=C, font="Arial 20 bold")
D.pack()


root.mainloop()

来自文件2的代码

from file1 import C
print(C)

最佳答案

发生这种情况是因为当您导入 python 文件时,您实际上是在运行整个文件以获取引用。当 file1 完整运行时,整个文件被解释并运行。这包括最后一行,root.mainloop()

您要使用的是检查当前文件是否为主文件的最佳实践。如果它不是当前的主程序,这将阻止它运行某些代码行。

您正在寻找这样的东西:

if __name__ == "__main__":
root.mainloop()

关于python - 使用 tkinter 时 import stament 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67047341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com