我的Python tkinter GUI为什么在我频繁点击返回按钮后关闭?

huangapple go评论106阅读模式
英文:

why does my python tkinter gui close after I spam the back button?

问题

以下是您要求的代码部分的中文翻译:

这是带有返回按钮的注册页面代码:

import tkinter as tk
import sqlite3
from tkinter import *
from tkinter import messagebox  # 导入消息框以显示错误消息
import re  # 导入正则表达式模块
import customtkinter
from PIL import ImageTk, Image


# 销毁此窗口并打开登录界面
def login():
    register_screen.destroy()
    import login  # 假设存在一个login.py文件以打开登录界面

def main():
    register_screen.destroy()
    import main


def register_user():
    # 获取用户名和密码
    username_value = username.get()
    password_value = password.get()
    
    # 检查密码要求
    # 检查密码中是否至少包含一个大写字母
    if not re.search(r"[A-Z]", password_value):
        error_label.config(text="密码必须包含至少一个大写字母", fg="red")
        return
    # 检查密码中是否至少包含一个数字
    if not re.search(r"\d", password_value):
        error_label.config(text="密码必须包含至少一个数字", fg="red")
        return
    # 检查密码中是否至少包含一个符号
    if not re.search(r"\W", password_value):
        error_label.config(text="密码必须包含至少一个符号", fg="red")
        return
    
    # 将用户插入数据库
    cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username_value, password_value))
    connection.commit()
    
    login()


# 注册界面设计
register_screen = tk.Tk()
register_screen.title("注册")
register_screen.geometry("500x800")
register_screen.resizable(width=False, height=False)

# 创建数据库连接
connection = sqlite3.connect("db/registration.db")
cursor = connection.cursor()

# 为注册创建一个表格
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")

# 背景图像
background_image_login = PhotoImage(file="assets/background2.png")
background_label_login = Label(register_screen, image=background_image_login)
background_label_login.place(x=0, y=0, relwidth=1, relheight=1)

# 创建一个空元组用于用户名和密码
username = StringVar()
password = StringVar()

# 为图像创建一个空标签
logo = ImageTk.PhotoImage(Image.open("assets/Logo.png").resize((180, 130), Image.ANTIALIAS))
logo1 = customtkinter.CTkButton(master=register_screen, image=logo, text="", compound="left", hover=False, bg_color="#020202")
logo1.place(relx=0.48, rely=0.2, anchor=CENTER)

# 创建一个空标签用于文本
username_label = Label(register_screen, text="用户名")
username_label.place(relx=0.5, rely=0.3, anchor=CENTER)

# 为用户名创建一个自定义输入框
username_entry = customtkinter.CTkEntry(master=register_screen, textvariable=username, placeholder_text="用户名", height=35, width=250)
username_entry.place(relx=0.5, rely=0.35, anchor=CENTER)

# 创建一个空标签用于文本
password_label = Label(register_screen, text="密码")
password_label.place(relx=0.5, rely=0.4, anchor=CENTER)

# 为密码创建一个自定义输入框
password_entry = customtkinter.CTkEntry(master=register_screen, textvariable=password, placeholder_text="密码", height=35, width=250, show="*")
password_entry.place(relx=0.5, rely=0.45, anchor=CENTER)

# 创建一个按钮
register_button = customtkinter.CTkButton(master=register_screen, text="注册", command=register_user, height=35, width=250)
register_button.place(relx=0.5, rely=0.55, anchor=CENTER)

# 创建一个空标签用于错误消息
error_label = Label(register_screen, text="", fg="red")
error_label.place(relx=0.5, rely=0.62, anchor=CENTER)

arrow_image = ImageTk.PhotoImage(Image.open("assets/hi.png").resize((50, 50), Image.ANTIALIAS))
arrow_button = customtkinter.CTkButton(master=register_screen, image=arrow_image, text="", compound="left" ,fg_color='black', hover_color='black', command=main) 
arrow_button.place(relx=0.1 , rely = 0.1, anchor = CENTER)

register_screen.mainloop()

# 关闭数据库连接
connection.close()

这是主页代码:

# 导入模块
import tkinter
from tkinter import *
import os
import customtkinter
from PIL import ImageTk, Image

root = Tk()
# 设计主屏幕
def main_screen():
    root.geometry("500x800")
    main_frame = Frame(root,bg ='#020202')
    main_frame.pack(padx=20)
    main_frame.pack()
    background_image = PhotoImage(file="assets/Aim high.png")
    background_label = Label(root, image=background_image)
    background_label.place(x=0, y=0, relwidth=1, relheight=1)
    root.title("帐户登录")
    top_text = Label(root, text="欢迎来到FitQuest", bg="#020202", font=("Calibri", 45))
    top_text.pack(pady=0, anchor=tkinter.CENTER)
    
    def register():
        root.destroy()
        import register
    
    def login():
        root.destroy()
        import login
    
    # 登录按钮
    Login_button = customtkinter.CTkButton(master=root, text="登录", command=login, height=35, width=250, bg_color="#020202")
    Login_button.place(relx=0.48, rely=0.3, anchor=tkinter.CENTER)
    # 注册按钮
    register_button = customtkinter.CTkButton(master=root, text="注册", command=register, height=35, width=250, bg_color="#020202")
    register_button.place(relx=0.48, rely=0.4, anchor=tkinter.CENTER)
    # 图标作为按钮
    logo = ImageTk.PhotoImage(Image.open("assets/Logo.png"), Image.ANTIALIAS)
    button1 = customtkinter.CTkButton(master=root, image=logo, text="", compound="left", hover=False, bg_color="#020202")
    button1.place(relx=0.48, rely=0.158, anchor=tkinter.CENTER)
 
    root.mainloop()

main_screen()

希望这些翻译对您有所帮助。如果您有任何其他

英文:

The problem with my code is that when I click on the back button which is the top left button, it goes back to the main screen and then I click on the register button which takes me to the register screen, it is fine and if I clikc the back button again, the GUI would close automally with nothing said in the terminal.

This is the register page with the back button

import sqlite3
from tkinter import *
from tkinter import messagebox  # Import messagebox for error messages
import re  # Import re module for regular expressions
import customtkinter
from PIL import ImageTk, Image
# Destroy this window and open the login screen
def login():
register_screen.destroy()
import login  # Assuming there is a login.py file to open the login screen
def main():
register_screen.destroy()
import main
def register_user():
# Get username and password
username_value = username.get()
password_value = password.get()
# Check password requirements
# Check if there is at least one capital letter in the password section
if not re.search(r"[A-Z]", password_value):
error_label.config(text="Password must contain at least one capital letter", fg="red")
return
# Check if there is at least one number in the password section
if not re.search(r"\d", password_value):
error_label.config(text="Password must contain at least one number", fg="red")
return
# Check if there is at least one symbol in the password section
if not re.search(r"\W", password_value):
error_label.config(text="Password must contain at least one symbol", fg="red")
return
# Insert the user into the database
cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username_value, password_value))
connection.commit()
login()
# Designing for registration
register_screen = tk.Tk()
register_screen.title("Register")
register_screen.geometry("500x800")
register_screen.resizable(width=False, height=False)
# Create a database connection
connection = sqlite3.connect("db/registration.db")
cursor = connection.cursor()
# Create a table for registration
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT)")
# Background image
background_image_login = PhotoImage(file="assets/background2.png")
background_label_login = Label(register_screen, image=background_image_login)
background_label_login.place(x=0, y=0, relwidth=1, relheight=1)
# Creating an empty tuple for username and password
username = StringVar()
password = StringVar()
# Create an empty label for the image
logo = ImageTk.PhotoImage(Image.open("assets/Logo.png").resize((180, 130), Image.ANTIALIAS))
logo1 = customtkinter.CTkButton(master=register_screen, image=logo, text="", compound="left", hover=False, bg_color="#020202")
logo1.place(relx=0.48, rely=0.2, anchor=CENTER)
# Create an empty label for the text
username_label = Label(register_screen, text="Username")
username_label.place(relx=0.5, rely=0.3, anchor=CENTER)
# Create a customentry widget for username
username_entry = customtkinter.CTkEntry(master=register_screen, textvariable=username, placeholder_text="Username", height=35, width=250)
username_entry.place(relx=0.5, rely=0.35, anchor=CENTER)
# Create an empty label for the text
password_label = Label(register_screen, text="Password")
password_label.place(relx=0.5, rely=0.4, anchor=CENTER)
# Create a customentry widget for password
password_entry = customtkinter.CTkEntry(master=register_screen, textvariable=password, placeholder_text="Password", height=35, width=250, show="*")
password_entry.place(relx=0.5, rely=0.45, anchor=CENTER)
# Create a button
register_button = customtkinter.CTkButton(master=register_screen, text="Register", command=register_user, height=35, width=250)
register_button.place(relx=0.5, rely=0.55, anchor=CENTER)
# Create an empty label for the error message
error_label = Label(register_screen, text="", fg="red")
error_label.place(relx=0.5, rely=0.62, anchor=CENTER)
arrow_image = ImageTk.PhotoImage(Image.open("assets/hi.png").resize((50, 50), Image.ANTIALIAS))
arrow_button = customtkinter.CTkButton(master= register_screen,image = arrow_image,text="", compound="left" ,fg_color='black', hover_color='black', command= main) 
arrow_button.place(relx=0.1 , rely = 0.1, anchor = CENTER)
register_screen.mainloop()
# Close the database connection
connection.close() 

This is the home page code

import tkinter
from tkinter import *
import os
import customtkinter
from PIL import ImageTk, Image
root = Tk()
# Designing the main screen
def main_screen():
root.geometry("500x800")
main_frame = Frame(root,bg ='#020202')
main_frame.pack(padx=20)
main_frame.pack()
background_image = PhotoImage(file="assets/Aim high.png")
background_label = Label(root,image = background_image)
background_label.place(x=0, y=0, relwidth = 1 , relheight = 1)
root.title("Account Login")
top_text=Label(root,text="Welcome to FitQuest",bg="#020202",font=("Calibri", 45))
top_text.pack(pady=0, anchor =tkinter.CENTER)
def register():
root.destroy()
import register
def login():
root.destroy()
import login
#Login button 
Login_button = customtkinter.CTkButton(master=root, text="Login", command=login, height = 35, width = 250,bg_color="#020202")
Login_button.place(relx=0.48, rely=0.3, anchor=tkinter.CENTER)
#register button
register_button = customtkinter.CTkButton(master=root, text="Register", command=register,height = 35, width = 250, bg_color="#020202" )
register_button.place(relx=0.48, rely=0.4, anchor=tkinter.CENTER)
#Logo act as a button 
logo = ImageTk.PhotoImage(Image.open("assets/Logo.png"),Image.ANTIALIAS)
button1 =customtkinter.CTkButton(master=root,image=logo,text="",compound="left" , hover=False, bg_color="#020202")
button1.place(relx=0.48, rely=0.158, anchor=tkinter.CENTER)
root.mainloop()
main_screen() 

答案1

得分: 1

一个import语句不必重新执行模块内容,在您的情况下,这正是发生的情况。在Python中,模块被缓存在sys.modules中,每个import语句首先检查该缓存,以确定模块是否已加载,如果已加载,则返回缓存的模块对象。

而不是销毁屏幕并重新导入模块,只需将初始化和析构代码放在函数内,无条件地导入模块,然后在必要时调用这些函数。

英文:

An import statement does not have to re-execute the module contents, and in your case that's exactly what happens. Modules in Python are cached in sys.modules, and every import statement checks against that cache first to determine if the module is already loaded, and if it is, the cached module object is returned.

Instead of destroying screens and reimporting modules, just put the initialization and deconstruction code inside functions, import modules unconditionally, and then call the functions when necessary

huangapple
  • 本文由 发表于 2023年7月20日 18:09:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定