Python 这个程序给了我一个循环导入错误,但仍然有效
因此,我有一个带有Tkinter的GUI,当我点击一个按钮时,它会切换屏幕,新屏幕上有一个返回按钮,返回到主屏幕。如果你关闭另一个屏幕,它会再次将你带回到主屏幕,如果你关闭主屏幕,应用程序会正常关闭。但是,当将主屏幕切换到另一个屏幕时,它完全可以正常工作,但无论如何,它都会出现此错误:Python 这个程序给了我一个循环导入错误,但仍然有效,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,因此,我有一个带有Tkinter的GUI,当我点击一个按钮时,它会切换屏幕,新屏幕上有一个返回按钮,返回到主屏幕。如果你关闭另一个屏幕,它会再次将你带回到主屏幕,如果你关闭主屏幕,应用程序会正常关闭。但是,当将主屏幕切换到另一个屏幕时,它完全可以正常工作,但无论如何,它都会出现此错误: Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\User\AppData\Local\
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1885, in __call__
return self.func(*args)
File "C:\Users\User\Desktop\Coding\Python\GmailSenderApp\GmailSenderApp.py", line 30, in <lambda>
button = tk.Button(root, text="Send Gmail without Attachments", font=('Courier', 14), command=lambda: screen1())
File "C:\Users\User\Desktop\Coding\Python\GmailSenderApp\GmailSenderApp.py", line 7, in screen1
Screen1.root.mainloop()
AttributeError: partially initialized module 'Screen1' has no attribute 'root' (most likely due to a circular import)
第二屏:
import tkinter as tk
import GmailSenderApp
def back():
root.destroy()
GmailSenderApp.root.mainloop()
HEIGHT = 500
WIDTH = 600
root = tk.Tk()
root.resizable(False, False)
root.title('Gmail Sender App')
icon = tk.PhotoImage(file='icon.png')
root.iconphoto(False, icon)
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
background_label = tk.Label(root, bg='#ffbe80')
background_label.place(relwidth=1, relheight=1)
title_label = tk.Label(root, bg='#80c1ff', text="Gmail Sender App", font=('Courier', 14))
title_label.place(width=root.winfo_screenwidth(), height=40, y=0, x=-375)
button = tk.Button(root, text="Back", font=('Courier', 14), command=lambda: back())
button.place(width=400, height=40, x=root.winfo_width() / 2, y=root.winfo_height() / 2)
root.mainloop()
那么我做错了什么
另外请注意:当再次单击按钮进入屏幕时,应用程序会崩溃
顺便说一句,由于导入文件时会执行全局范围内的所有代码,并且该代码可能需要最初运行的文件中的函数,因此可能会导致循环错误 我试着运行你的代码,尽管它对我来说运行不正常,但我知道你想要实现什么。您正在尝试实现选项卡功能,但每次切换到选项卡时都会打开一个新窗口。因此,我建议使用tkinter内置的选项卡
from tkinter import ttk
tabs = ttk.Notebook(root)
Screen1 = ttk.Frame(tabs) # defining a new tab
tabs.add(Screen1, text='Screen1') # adding the new tab to the root
GmailSenderApp = ttk.Frame(tabs)
tabs.add(GmailSenderApp, text='GmailSenderApp')
现在,您不需要为每个选项卡创建一个新文件,所以将所有代码保存在一个文件中,同时将按钮之类的东西放置在根目录中,而不是将它们直接放置到选项卡中
例如,我想在Screen1选项卡中添加一个按钮:
button = tk.Button(Screen1, text="Back", font=('Courier', 14), command=lambda: back())
button.place(width=400, height=40, x=root.winfo_width() / 2, y=root.winfo_height() / 2)
总而言之,您必须做的更改是添加我编写的第一段代码,将所有代码放在一个文件中,并将按钮和标题之类的第一个参数从根目录替换为所属的选项卡
如果有什么不清楚的,请随时问我
button = tk.Button(Screen1, text="Back", font=('Courier', 14), command=lambda: back())
button.place(width=400, height=40, x=root.winfo_width() / 2, y=root.winfo_height() / 2)