从一个类到另一个类获取变量

时间:2018-09-28 12:09:38

标签: python-3.x class tkinter

我想从一个类到另一个类获取一个变量。 我要使用的变量是配置文件,该文件位于第129行。我想在该类之外使用该变量,并在代码底部向下使用AddJob()类。如果有人可以给我一个解决方案,我将不胜感激,因为我一直在努力使它工作几天。

import tkinter
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
from tkinter.scrolledtext import ScrolledText

import sqlite3
from sqlite3 import Error

import webbrowser
import re

Background = ("WHITE")
LARGE_FONT = ("Verdana", 9)
HOME_FONT = ("Times", 15, "bold")
EMAIL_FONT = ("times", 9)


def DataBase():
    with sqlite3.connect("UserInfo.db") as db:
        cursor = db.cursor()

    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users(
    userID INTEGER PRIMARY KEY,

    username STRING,
    password STRING, 
    firstname STRING, 
    surname STRING,
    email STRING);
    ''')

    cursor.execute ('''
    CREATE TABLE IF NOT EXISTS jobs(
    jobID INTEGER PRIMARY KEY,
    userID
    jobtitle STRING,
    jobdescript STRING);
    ''')



class MsgBox(tkinter.Toplevel):

    def __init__(self, title = "", message = ""):
        tkinter.Toplevel.__init__(self)

        self.title(title)

        self.label = tkinter.Label(self, text = message)
        self.label['bg'] = 'white'
        self.label.pack(ipadx = 10, ipady = 10, fill = 'both', expand = True)

        self.button = tkinter.Button(self, text = "OK")
        self.button['command'] = self.destroy
        self.button.pack(pady = 10, padx = 10, ipadx = 20, side = 'right')


class JobApp(tk.Tk):
    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side = "top", fill = "both", expand = True)
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)

        self.frames = {}


        #this is where you add a page to the program so you can add different functions
        for F in (LoginPage, SignUp, HomePage, MenuPage, MapPage, ProfilePage, SettingsPage, JobsPage, AddJob):

            frame = F(container, self)

            self.frames[F] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")

        self.show_frame(LoginPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

    DataBase()


class LoginPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        self.Logo = PhotoImage(file = "Logo.gif")

        def Log_in():

            with sqlite3.connect("UserInfo.db") as db:
                cursor = db.cursor()


            user = (self.UserEntry.get())
            Pass = (self.PassEntry.get())

            if user == "" or Pass == "":
                msg = MsgBox("", "Make sure to fill all the boxes\nPlease try again")
                msg.label['font'] = 'Verdana 10'
                msg.button['text'] = 'Close'
                msg.button.pack(expand = True)

            else:

                dictionary = {}
                cursor.execute("SELECT username, password FROM users")
                for pword in cursor.fetchall():
                    (key ,val) = tuple(pword)
                    dictionary[str(key)] = val



                if user in dictionary:
                    if dictionary[user] == Pass:

                        sql = '''SELECT userID FROM users WHERE username = ?'''
                        cursor.execute(sql, (user,))

                        profile = cursor.fetchall()

                        controller.show_frame(HomePage)
                        self.UserEntry.delete(0, 'end')
                        self.PassEntry.delete(0, 'end')

                    else:
                        messagebox.showinfo("", "Enter the correct password")
                        self.PassEntry.delete(0, 'end')

        self.logo = tk.Label(self, image = self.Logo)

        self.User = tk.Label(self, text = "User Name:").place(x = 72, y = 130)
        self.Pass = tk.Label(self, text = "Password:").place(x = 80, y = 155)

        self.UserEntry = Entry(self)

        self.PassEntry = Entry(self, show = '*')

        self.login = ttk.Button(self, text = "Login", command = Log_in)
        self.signup = ttk.Button(self, text = "Create account",
                                 command = lambda:controller.show_frame(SignUp))

        self.UserEntry.place(width = 100, height = 20, x = 140, y = 130)
        self.PassEntry.place(width = 100, height = 20, x = 140, y = 155)
        self.login.place(x = 80, y = 180)
        self.signup.place(x = 160, y = 180)
        self.logo.place(x = 110, y = 20)


class SignUp(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)




        def Save_info():

            DataBase()

            with sqlite3.connect("UserInfo.db") as db:
                cursor = db.cursor()

            FnameEntry = self.FnameEntry.get()
            SnameEntry = self.SnameEntry.get()
            EmailEntry = self.EmailEntry.get()
            UserNameEntry = self.UserNameEntry.get()
            PassWordEntry = self.PassWordEntry.get()
            RenterPasswordEntry = self.RenterPasswordEntry.get()

            check = []
            cursor.execute("SELECT * FROM users")
            for row in cursor.fetchall():
                check.append(row)
            print (check)


            if not re.match(r"[^@]+@[^@]+\.[^@]+", EmailEntry):
                messagebox.showinfo("ERROR", "the email that you entered was not valid\nPlease try again")

            if len(FnameEntry) == 0 or len(SnameEntry) == 0 or len(EmailEntry) == 0 or len(UserNameEntry) == 0 or len(PassWordEntry) == 0 or len(RenterPasswordEntry) == 0:
                messagebox.showinfo("No fill", "You didn't fill all the fields")
            else:
                if len(UserNameEntry) < 6:
                    messagebox.showinfo("Not long enough", "your username wasn't long enough\nPlease try again")
                else:
                    if len(PassWordEntry) < 6:
                        messagebox.showinfo("Not long enough", "Your password wasn't long enough\nPlease try again")
                    else:
                        if RenterPasswordEntry != PassWordEntry:
                            messagebox.showinfo("pass word match up", "Your passwords didn't seem to match up\nPlease try again")
                        else:
                            if UserNameEntry in check:
                                messagebox.showinfo("", "The user name that you entered already exsists\nPlease enter a different one")
                                self.UserNameEntry.delete(0, 'end')
                                self.PassWordEntry.delete(0, 'end')
                                self.RenterPasswordEntry.delete(0, 'end')
                            else:
                                YesNo = messagebox.askokcancel("Continue", "would you like to go back to the login page")
                                if YesNo == True:

                                    self.FnameEntry.delete(0, 'end')
                                    self.SnameEntry.delete(0, 'end')
                                    self.EmailEntry.delete(0, 'end')
                                    self.UserNameEntry.delete(0, 'end')
                                    self.PassWordEntry.delete(0, 'end')
                                    self.RenterPasswordEntry.delete(0, 'end')



                                    cursor.execute("""
                                    INSERT INTO users (username,password,firstname,surname,email)
                                    VALUES (?, ?, ?, ?, ?)
                                    """, (UserNameEntry, PassWordEntry, FnameEntry, SnameEntry, EmailEntry))
                                    db.commit()

                                    cursor.execute("SELECT * FROM users")
                                    print(cursor.fetchall())                                            

                                    controller.show_frame(LoginPage)

        self.x = ttk.Label(self, text = "fill in the information to create an account.\n\nBoxes with * next to them must be filled in.\nYour Username must be longer than 6 characters.\nYour password must be longer than 6 characters.\n", font = LARGE_FONT).grid(row = 0, column = 0, columnspan = 2)
        self.Fname = ttk.Label(self, text = "First Name *:", font = LARGE_FONT).grid(row = 1, sticky = "e")
        self.Sname = ttk.Label(self, text = "Surname *:", font = LARGE_FONT).grid(row = 2, sticky = "e")
        self.Email = ttk.Label(self, text = "Email Address *:", font = LARGE_FONT).grid(row = 3, sticky = "e")
        self.UserName = ttk.Label(self, text = "User name *:", font = LARGE_FONT).grid(row = 4, sticky = "e")
        self.PassWord = ttk.Label(self, text = "Password *:", font = LARGE_FONT).grid(row = 5, sticky = "e")
        self.ReneterPassword = ttk.Label(self, text = "Confirm password *:", font = LARGE_FONT).grid(row = 6, sticky = "e")

        self.blank = ttk.Label(self, text = "").grid(row = 8)
        Continue = ttk.Button(self, text = "Continue",
                              command = Save_info).grid(row = 9, rowspan = 2, stick = "e")
        Cancel = ttk.Button(self , text = "Cancel",
                            command= lambda:controller.show_frame(LoginPage)).grid(row = 9, column = 1, stick = "w")

        self.FnameEntry = Entry(self)
        self.SnameEntry = Entry(self)
        self.EmailEntry = Entry(self)
        self.UserNameEntry = Entry(self)
        self.PassWordEntry = Entry(self)
        self.RenterPasswordEntry = Entry(self)

        self.FnameEntry.grid(row = 1, column = 1, sticky = "w")
        self.SnameEntry.grid(row = 2, column = 1, sticky = "w")
        self.EmailEntry.grid(row = 3, column = 1, sticky = "w")
        self.UserNameEntry.grid(row = 4, column = 1, sticky = "w")
        self.PassWordEntry.grid(row = 5, column = 1, sticky = "w")
        self.RenterPasswordEntry.grid(row = 6, column = 1, sticky = "w")


class HomePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        def on_entry_click(event):
            if self.postcode.get() == 'Postcode':
                self.postcode.delete(0, "end")
                self.postcode.insert(0, '')
                self.postcode.config(fg = 'black')

        def on_focusout(event):
            if self.postcode.get() == '':
                self.postcode.delete(0, "end")
                self.postcode.insert(0, 'Postcode')
                self.postcode.config(fg = 'grey')

        def on_entry_click2(event):
            if self.searchjob.get() == 'Enter a job you want to search for..':
                self.searchjob.delete(0, "end")
                self.searchjob.insert(0, '')
                self.searchjob.config(fg = 'black')

        def on_focusout2(event):
            if self.searchjob.get() == '':
                self.searchjob.delete(0, "end")
                self.searchjob.insert(0, 'Enter a job you want to search for..')

                self.searchjob.config(fg = 'grey')

        Homepagecanvas = Canvas(self, width = 320, height = 568)
        Homepagecanvas.pack()

        TopBarHome = Homepagecanvas.create_rectangle(0, 0, 320, 50, fill = 'light grey')
        Home = Homepagecanvas.create_text((80, 25), text = "Home", font = HOME_FONT)

        MenuButton = ttk.Button(self, text = "Menu",
                            command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)

        self.postcode = Entry(self)
        self.searchjob = Entry(self)

        self.postcode.insert(0, 'Postcode')
        self.postcode.bind('<FocusIn>', on_entry_click)
        self.postcode.bind('<FocusOut>', on_focusout)
        self.postcode.config(fg = 'grey')
        self.postcode.place(width = 60, height = 30, x = 10, y = 60)

        self.searchjob.insert(0, 'Enter a job you want to search for..')
        self.searchjob.bind('<FocusIn>', on_entry_click2)
        self.searchjob.bind('<FocusOut>', on_focusout2)
        self.searchjob.config(fg = 'grey')
        self.searchjob.place(width = 220, height = 30, x = 80, y = 60)

        scrollbar = Scrollbar(self)
        scrollbar.place(width = 10, height =
                        450, x = 10, y = 100)

        Joblist = Listbox(self, yscrollcommand = scrollbar.set)
        for line in range(100):
            Joblist.insert(END, "This is line number " + str(line))

        Joblist.place(height = 450, width = 280, x = 25, y = 100)
        scrollbar.config(command = Joblist.yview)


class MenuPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        Homepagecanvas = Canvas(self, width = 320, height = 568)
        Homepagecanvas.pack()

        TopBarHome = Homepagecanvas.create_rectangle(0, 0, 320, 50, fill = 'light grey')
        Home = Homepagecanvas.create_text((40, 15), text = "Menu", font = HOME_FONT)
        Home = Homepagecanvas.create_text((160, 35), text = "here you can navigate to other pages in the application")

        Home = tk.Button(self,
                         text = "Home Page",
                         relief = GROOVE,
                         command = lambda:controller.show_frame(HomePage)).place(width = 100, height = 30, x = 10, y = 60)

        Map = tk.Button(self,
                        text = "Map",
                        relief = GROOVE,
                        command = lambda:controller.show_frame(MapPage)).place(width = 100, height = 30, x = 10, y = 90)

        Profile = tk.Button(self,
                            text = "Profile",
                            relief = GROOVE,
                            command = lambda:controller.show_frame(ProfilePage)).place(width = 100, height = 30, x = 10, y = 120)

        Settings = tk.Button(self,
                            text = "Settings",
                            relief = GROOVE,
                            command = lambda:controller.show_frame(SettingsPage)).place(width = 100, height = 30, x = 10, y = 150)

        Jobs = tk.Button(self,
                            text = "Jobs",
                            relief = GROOVE,
                            command = lambda:controller.show_frame(JobsPage)).place(width = 100, height = 30, x = 10, y = 180)



class MapPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        MapPageCanvas = Canvas(self, width = 320, height = 568)
        MapPageCanvas.pack()

        TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
                                                fill = 'light grey')
        Home = MapPageCanvas.create_text((80, 25),
                                         text = "Map",
                                         font = HOME_FONT)

        MenuButton = ttk.Button(self, text = "Menu",
                            command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)


class ProfilePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        def on_entry_click(event):
            if self.postcode.get() == 'Postcode':
                self.postcode.delete(0, "end")
                self.postcode.insert(0, '')
                self.postcode.config(fg = 'black')

        def on_focusout(event):
            if self.postcode.get() == '':
                self.postcode.delete(0, "end")
                self.postcode.insert(0, 'Postcode')
                self.postcode.config(fg = 'grey')

        ProfilePageCanvas = Canvas(self, width = 320, height = 568)
        ProfilePageCanvas.pack()

        TopBar = ProfilePageCanvas.create_rectangle(0, 0, 320, 50,
                                                    fill = 'light grey')
        Profile = ProfilePageCanvas.create_text((80, 25), text = "Profile",
                                                font = HOME_FONT)

        MenuButton = ttk.Button(self, text = "Menu",
                            command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)

        def logout():
            result = messagebox.askokcancel("Logout", "would you like to logout")
            if result == True:
                controller.show_frame(LoginPage)

        Logout = ttk.Button(self, text = "Logout",
                            command = logout).place(width = 60, height = 40, x = 255 , y = 5)


class SettingsPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        MapPageCanvas = Canvas(self, width = 320, height = 568)
        MapPageCanvas.pack()

        TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
                                                fill = 'light grey')
        Home = MapPageCanvas.create_text((90, 25),
                                         text = "Settings",
                                         font = HOME_FONT)

        MenuButton = ttk.Button(self, text = "Menu",
                            command = lambda:controller.show_frame(MenuPage)
                            ).place(height = 40, width = 40, x = 5, y = 5)

        def BG():
            app.configure(background = Background)

        def Toggle():

            if DarkTheme.config('relief')[-1] == 'flat':
                DarkTheme.config(relief = "sunken", bg = 'grey')
            else:
                DarkTheme.config(relief = "flat", bg = 'white')

            Background = "DARK GRAY"

            BG()

        DarkTheme = tk.Button(self,
                              bg = 'white',
                              highlightbackground = 'black',
                              text = "Dark Theme",
                              pady = 5, padx = 5,
                              relief = "flat",
                              command = Toggle)
        DarkTheme.place(x = 5, y = 60)


class JobsPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        MapPageCanvas = Canvas(self, width = 320, height = 568)
        MapPageCanvas.pack()

        TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
                                                fill = 'light grey')
        Home = MapPageCanvas.create_text((80, 25),
                                         text = "Jobs",
                                         font = HOME_FONT)

        MenuButton = ttk.Button(self, text = "Menu",
                            command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)

        addjob = ttk.Button(self, text = "Add Job",
                            command = lambda:controller.show_frame(AddJob)).place(height = 40, width = 60, x = 255, y = 5)







class AddJob(tk.Frame, LoginPage):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)

        def dbAddJob():


            JobT = self.Jt.get("1.0", 'end').rstrip('\n')
            JobD = self.Jd.get("1.0", 'end').rstrip('\n')

            with sqlite3.connect("UserInfo.db") as db:
                cursor = db.cursor()

            if JobT == "" or JobD == "":
                messagebox.showinfo("Invalid","please fill in the boxes or cancel") 
            else:
                aj = messagebox.askokcancel("Continue", "Job added click ok to continue\nor cancel or change what you have added")
                if aj == True:
                    cursor.execute("""
                    INSERT INTO jobs (jobtitle, jobdescript)
                    VALUES (?, ?)
                    """, (JobT, JobD))
                    db.commit()
                    self.Jt.delete('1.0', END)
                    self.Jd.delete('1.0', END)

                    controller.show_frame(JobsPage)

            cursor.execute("SELECT * FROM jobs")
            print(cursor.fetchall())

        MapPageCanvas = Canvas(self, width = 320, height = 568)
        MapPageCanvas.pack()

        TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
                                                fill = 'light grey')
        Home = MapPageCanvas.create_text((100, 25),
                                         text = "Add a Job",
                                         font = HOME_FONT)

        MenuButton = ttk.Button(self, text = "Back",
                            command = lambda:controller.show_frame(JobsPage)).place(height = 40, width = 40, x = 5, y = 5)

        self.Addjobbutton = ttk.Button(self, text = "Add",
                                 command = dbAddJob).place(width = 60, height = 30, x = 90, y = 520)

        self.Cancel = ttk.Button(self, text = "cancel",
                                command = lambda:controller.show_frame(JobsPage)).place(width = 60, height = 30, x = 170, y = 520)

        self.Jt = ScrolledText(self)
        self.Jd = ScrolledText(self)

        self.Jt.place(height = 30, width = 310, x = 5, y = 60)
        self.Jd.place(height = 400, width = 310, x = 5, y = 100)




app = JobApp()
app.geometry('320x568')
app.resizable(0,0)
app.mainloop()

1 个答案:

答案 0 :(得分:0)

您是否要使其成为全局变量,例如?

sound = None

class Cat(object):
     global sound

     """
     All your code
     """

     sound = "meow"

现在,如果您使用“全局声音”,则可以从任何地方访问全局变量,现在声音会返回:

>>> sound
'meow'

这样,您就可以在没有类或函数的情况下访问变量。