首页 > 编程问答 >如何从另一个文件运行 python 文件

如何从另一个文件运行 python 文件

时间:2024-07-25 15:56:14浏览次数:9  
标签:python python-3.x file oop methods

我正在尝试从另一个名为 LoginOrReg 的文件运行一个名为 HabitTracker 的 python 文件,但是当我这样做时,它会重新运行 LoginOrReg 文件。

我已经尝试过这个

class LoginOrReg:
    def __init__(self, db, cursor, login_username, data):
        self.db = mysql.connector.connect(host = '**', user = '**', password= '**', database="**")
        self.cursor = self.db.cursor()
        self.login_username = login_username
        self.data = data

    # Asks user if they want to login or register
    def login_or_reg(self, root):
        self.root = customtkinter.CTk()
        self.root.geometry('175x175')
        self.login_button = customtkinter.CTkButton(self.root, text='Login', command=self.login).pack(pady=20)
        self.reg_button = customtkinter.CTkButton(self.root, text='Register', command=self.reg_user).pack(pady=10)
        self.root.mainloop()
def login(self):
        self.login_window = customtkinter.CTk()
        self.login_window.geometry('400x400')
        self.login_username_entry = customtkinter.CTkEntry(self.login_window, placeholder_text ='Enter Your Username')
        self.login_username_entry.pack(pady=30)
        self.login_username = self.login_username_entry.get() 
        self.login_password_entry = customtkinter.CTkEntry(self.login_window, placeholder_text ='Enter Your Password')
        self.login_password_entry.pack(pady=30)
        self.login_password = self.login_password_entry.get()
        self.log_user_in_button = customtkinter.CTkButton(self.login_window, text = 'Login', command = self.log_user_in)
        self.log_user_in_button.pack(pady=30)
        self.reg_button = customtkinter.CTkButton(self.login_window, text = 'Register New User', command = self.reg_user)
        self.reg_button.pack(pady=20)
        self.login_window.mainloop()

    #Logs the user in
    def log_user_in(self):
        import HabitTracker as HT
        self.habit = HT.HabitTracker(main_window=' ', sorting_options= ' ', sort= ' ', login= ' ')
        self.cursor.execute('SELECT username AND password, COUNT(*) FROM users WHERE username=%s AND password=%s GROUP BY username',(self.login_username_entry.get(), self.login_password_entry.get()))
        self.cursor.fetchall()
        self.row_count = self.cursor.rowcount
        if self.row_count == 1:
            self.cursor.execute('SELECT userID FROM users WHERE username=%s AND password=%s',(self.login_username_entry.get(), self.login_password_entry.get()))
            self.data = self.cursor.fetchone()
            print(self.data)
            for entry in self.data:
                self.user_id = self.data[0]
            self.habit.main_menu()
        else:
            self.my_label = customtkinter.CTkLabel(self.login_window, text = "User Not Found. Please Try Again.", font=('Helvetica', 10)).pack(pady=10)
login_reg = LoginOrReg(db = " ", cursor=" ", login_username= ' ', data = ' ')
login_reg.login_or_reg(root=" ")

如您所见,我已导入文件 Habit Tracker作为我的“log_user_in”方法中的 HT。 当我单击登录功能中规定的登录按钮时,我认为它甚至不运行 Log_user_in 函数,因为我放在那里的打印语句没有显示在终端中。我的目标是运行 HabitTracker 文件中的 Main_menu 方法。

这是我在主文件中导入 LoginOrReg 文件和类的位置:

class HabitTracker:
def __init__(self, main_window, sorting_options, sort, login) -> None:
    self.main_window = main_window 
    self.db = mysql.connector.connect(host = '***', user = '**', password= '**', database="**")
    self.cursor = self.db.cursor()
    self.sorting_options = sorting_options
    self.sort = sort 
    self.login = login
    
def main_menu(self):
    import LoginOrReg as LR
    self.login = LR.LoginOrReg(db=' ', cursor= ' ', login_username=' ', data= ' ')
    self.date = datetime.today()
    self.main_window = customtkinter.CTk()
    self.main_window.geometry('1080x720')
    self.sorting_options = ['Daily', 'Weekly', 'Monthly', 'Highest Streak',]
    self.mylabel = customtkinter.CTkLabel(self.main_window, text='Welcome {}'.format(self.login.login_username), font=('Arial', 40)).pack(pady=5)
    self.sort = customtkinter.CTkComboBox(self.main_window, values= self.sorting_options, command= sort_by.sort_by)
    self.sort.set('Sort By')
    self.sort.pack(pady=10)
    self.create_new_habit_button = customtkinter.CTkButton(self.main_window, text='Create New Habit', command=create_habit.create_habit, fg_color='green').pack(pady=20)
    self.cursor.execute('SELECT habit_name FROM habit WHERE user_id=%s GROUP BY habit_name', (self.login.data))
    self.habits = self.cursor.fetchall()
    self.j = 0
    for j in self.habits:
        self.habit_button = customtkinter.CTkButton(self.main_window, text=self.habits[self.j], command=lambda k = self.habits[self.j]: edit_habit.edit_habit(k))
        self.habit_button.pack(pady=10)
        self.j = self.j + 1
    self.main_window.mainloop() 

habit_tracker = HabitTracker(main_window= ' ', sorting_options= ' ', sort = " ", login=' ')

该问题源于在事件循环仍在运行时创建新的顶级窗口(使用 Tk() CTk() )。这会导致不可预测的行为,并且会中断预期的程序流程。

以下是如何解决此问题的分解方法,以及对代码进行更清晰、更易于管理的调整:

HabitTracker.py

import customtkinter
import mysql.connector
from datetime import datetime

class HabitTracker:
    def __init__(self, main_window, user_id):
        self.main_window = main_window
        self.user_id = user_id
        self.db = mysql.connector.connect(host='***', user='**', password='**', database="**")
        self.cursor = self.db.cursor()

    def main_menu(self):
        self.main_window.destroy()  # 关闭登录窗口

        self.main_window = customtkinter.CTk()
        self.main_window.geometry('1080x720')
        self.main_window.title("Habit Tracker")

        self.date = datetime.today()
        customtkinter.CTkLabel(self.main_window, text=f'欢迎 {self.user_id}', font=('Arial', 40)).pack(pady=5)

        sorting_options = ['Daily', 'Weekly', 'Monthly', 'Highest Streak']
        self.sort = customtkinter.CTkComboBox(self.main_window, values=sorting_options) 
        self.sort.set('排序方式')
        self.sort.pack(pady=10)

        customtkinter.CTkButton(self.main_window, text='创建新习惯', command=self.create_habit, fg_color='green').pack(pady=20)

        self.cursor.execute('SELECT habit_name FROM habit WHERE user_id=%s GROUP BY habit_name', (self.user_id,))
        habits = self.cursor.fetchall()

        for j, habit in enumerate(habits):
            customtkinter.CTkButton(self.main_window, text=habit[0], command=lambda h=habit[0]: self.edit_habit(h)).pack(pady=10)

        self.main_window.mainloop() 

    def create_habit(self):
        # 在此处添加创建习惯的逻辑
        pass

    def edit_habit(self, habit_name):
        # 在此处添加编辑习惯的逻辑
        pass

#  我们将在登录成功后创建 HabitTracker 实例

LoginOrReg.py

import customtkinter
import mysql.connector
from HabitTracker import HabitTracker 

class LoginOrReg:
    def __init__(self):
        self.db = mysql.connector.connect(host='**', user='**', password='**', database="**")
        self.cursor = self.db.cursor()

        self.root = customtkinter.CTk()
        self.root.geometry('175x175')
        self.root.title("登录或注册")

        customtkinter.CTkButton(self.root, text='登录', command=self.login).pack(pady=20)
        customtkinter.CTkButton(self.root, text='注册', command=self.reg_user).pack(pady=10)

        self.root.mainloop()

    def login(self):
        self.login_window = customtkinter.CTk()
        self.login_window.geometry('400x400')
        self.login_window.title("登录")

        self.login_username_entry = customtkinter.CTkEntry(self.login_window, placeholder_text='输入的用户名')
        self.login_username_entry.pack(pady=30)

        self.login_password_entry = customtkinter.CTkEntry(self.login_window, placeholder_text='输入的密码', show="*")
        self.login_password_entry.pack(pady=30)

        customtkinter.CTkButton(self.login_window, text='登录', command=self.log_user_in).pack(pady=30)
        customtkinter.CTkButton(self.login_window, text='注册新用户', command=self.reg_user).pack(pady=20)

    def log_user_in(self):
        username = self.login_username_entry.get()
        password = self.login_password_entry.get()

        self.cursor.execute('SELECT userID, COUNT(*) FROM users WHERE username=%s AND password=%s GROUP BY username', (username, password))
        result = self.cursor.fetchone()

        if result and result[1] == 1:
            user_id = result[0]
            self.login_window.destroy() # 关闭登录窗口
            habit_tracker = HabitTracker(self.root, user_id)  # 使用主窗口作为父级
            habit_tracker.main_menu()
        else:
            customtkinter.CTkLabel(self.login_window, text="用户未找到。请重试。", font=('Helvetica', 10)).pack(pady=10)

    def reg_user(self):
        #  在 此处添加用户注册逻辑
        pass

if __name__ == "__main__":
    login_reg = LoginOrReg()

说明:

  1. 分离窗口管理: 不要为每个窗口创建新的 CTk() 实例。在 LoginOrReg 中,我们保留一个主 root 窗口,并根据需要创建和销毁子窗口(如 login_window )。
  2. 登录成功后的流程: log_user_in 中,成功登录后,我们创建 HabitTracker 实例,将其传递给主 root 窗口,然后调用 habit_tracker.main_menu()
  3. 清除代码: 我删除了一些不必要的参数并将代码格式化得更清晰。

通过这些更改,的程序流程应该会得到改善,并且在登录后成功打开主菜单。

标签:python,python-3.x,file,oop,methods
From: 78784053

相关文章

  • Python的字典和集合
    一、字典1.定义字典字典和列表虽然类似,但是字典是无序的可变序列,并且可以像查字典一样去查找。字典的元素都是成对出现的,每个元素都是由冒号“:”和键值对(“:”左边的称为键或者Key,“:”右边的称为值或者Value)构成的,用“{}”标识,元素之间用逗号“‘,”分隔。字典的键必须是唯一......
  • 在Python中字典是如何通过哈希表实现的以及哈希冲突是如何解决的
    哈希表(散列表)的工作原理哈希表是一种使用哈希函数组织数据,以支持快速插入和搜索的数据结构。它通过哈希函数将输入的键(key)映射到表中的一个位置(即索引或槽位),从而以接近常数时间复杂度进行查找、插入和删除操作。哈希表的基本工作流程如下:哈希函数:哈希函数接受一个输入(键),并......
  • python cobs协议编解码算法demo
    1.SummaryCOBS(ConsistentOverheadByteStuffing)是一种算法,直译为一致的开销字节填充。简而言之,无论数据包的内容如何,都能通过产生高效可靠明确的数据包帧,从而使接受端能够从损坏的包中恢复。通常使用0x00来作为数据包的分隔符,即切割数据包的片分隔符。当使用0x00作为......
  • 如何将unicode编码为字节,以便可以检索到原始字符串?在Python 3.11中
    在python3.11中,我们可以对字符串进行编码,如:string.encode('ascii','backslashreplace')这对于说:hellö=>hell\\xf6但是当我插入时hellöw\\xf6rldIgethell\\xf6w\\xf6rld(注意第二个有一个看起来像字符转义序列的文字部分)......
  • python flask允许跨域
    flask接口支持跨域设置方法在Flask中,可以通过安装flask-cors扩展来支持跨域请求。下面是使用flask-cors扩展的示例代码:fromflaskimportFlaskfromflask_corsimportCORS#ipinstallflask-corsapp=Flask(__name__)CORS(app)可以通过CORS扩展的origins参数......
  • Makefile知识点总结(Linux下开发Risc-V单片机实例)
    Makefile会不会写makefile,从一个侧面决定一个人是否具备完成大型工程的能力。Makefile和make命令一起配合使用,为什么要使用makefile,原因以及优点在下文解释。简单辨析一下建立工程的三种方式Makefile使用非常广泛,通用性强,可跨平台但是语法比较严格,写一个通用,便于管理......
  • 在 Python 中动态定义文字字符串排列的并集
    我有一个字符串列表:strings=['a','b','c']我想声明列表中所有可能的有序对的Union类型。硬编码,这看起来像:Literal我如何动态定义CustomType=Literal['ab','ac','aa','ba','bb','bc�......
  • 关于 Python 中装饰器缓存的困惑
    我正在使用Python装饰器来实现函数的缓存。我了解缓存结果以提高性能的基本概念,但我正在努力解决如何处理不同的函数参数并确保底层数据更改时缓存更新。我已经实现了一个基本装饰器,它将函数结果存储在基于参数的字典。但是,此方法无法处理函数参数可能具有复杂结构(如嵌套列......
  • Python:__add__ 和 +,浮点数和整数的不同行为
    当将整数值添加到浮点值时,我意识到如果在浮点上调用该方法可以正常工作,例如:__add__但如果在整数上调用则不行:>>>n=2.0>>>m=1>>>n.__add__(m)3.0起初我认为|||只是对>>>m.__add__(n)NotImplemented和__add__类型的实现方式不同(例如f......
  • python中scrapy爬取数据get()与getall()区别
    在使用scrapy进行爬取数据的时候,有些时候需要爬取的是一段文本,或者一个div里面有很多内容,这时候我们就要使用到get()或者getall()来获取数据: get():是获取的满足条件的第一个数据。getall():是获取的满足条件的所有数据。scrapyget()getall()原理在Scrapy中,get(......