Python Forum
How to share a variable between two Python classes?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to share a variable between two Python classes?
#1
How to share a variable between two Python classes?
I am not an experienced programmer so please keep that in mind. I have a made an application with Tkinter, it's called a dice rolling simulator. The code contains three classes:

- The login screen (class 1)
- The privacy terms (class 2) (subclass class 1)
- The game-screen (class 3)

So basically the players have to read the privacy terms and press the button ok, to acknowledge that they have read the privacy terms. I am trying to make a realistic game. They cannot play the game until they have read the privacy terms.

My question: How can iI pass a variable from class 2 to class 1? In

In class 1 i have declared a variable start_game = False and in class 2 if the user has read the terms than I change the variable to True.

How can I pass the adjusted variable back to class 1 so that the users can play start the game.

If they haven't read the terms and they try to start the game than a error message pops up.

I hope I have made it clear to you.

Here under is my code:
from tkinter import *
import tkinter.messagebox
from tkinter import ttk 
import random
import os
import time
import datetime
from PIL import Image
from PIL import ImageTk
import webbrowser
from playsound import playsound
import pyttsx3
from tkinter import font

#---------WINDOW-----------------------
def main():
        window = Tk()
        DobbelsteenApp = Dobbelsteeninlog(window)     

class Dobbelsteeninlog:
            
        def __init__(self, window):
                
                #---------Window-----------------------
                self.window = window
                self.window.title("Inlog Dice Rolling ")
                
                self.window.geometry("975x750+0+0")
                self.window.config(bg="gray24")
                self.frame = Frame(self.window, bg="gray24")
                self.frame.grid(row=0,column=0)
                
                #---------Variabele----------------------
                self.Username1   = StringVar()
                self.Username2   = StringVar()

                
                
                 #-------LABEL-------------------------
                
                self.lblTitle = Label(self.frame, text="Login Dice Rolling",  font=('Times New Roman', 70,'bold'), bg="gray24", fg="Paleturquoise3")
                self.lblTitle.grid(row=0,column=0, columnspan=2, pady=20)
                
                #---------Frame-------------------
                self.loginframe1 = LabelFrame(self.frame, width = 850, height= 225, text='login', bd=20,
                                              font=('Times New Roman', 10,'bold'),bg="gray24", fg="Paleturquoise3")
                self.loginframe1.grid(row=1,column=0)
                
                self.loginframe2 = LabelFrame(self.frame, width = 900, height= 225, bd=20,
                                              font=('Times New Roman', 10,'bold'),bg="gray24", fg="Paleturquoise3")
                self.loginframe2.grid(row=2,column=0)
                
                self.loginframe3 = LabelFrame(self.frame, width = 900, height= 150, bd=0,
                                              font=('Times New Roman', 10,'bold'),bg="gray24", fg="Paleturquoise3")
                self.loginframe3.grid(row=3,column=0)

                self.loginframe4 = LabelFrame(self.frame, width = 900, height= 150, bd=0,
                                              font=('Times New Roman', 10,'bold'),bg="gray24", fg="Paleturquoise3")
                self.loginframe4.grid(row=4,column=0)

                self.loginframe41 = LabelFrame(self.loginframe4, width = 450, height= 225, bd=0,
                                              font=('Times New Roman', 10,'bold'),bg="gray24", fg="Paleturquoise3")
                self.loginframe41.grid(row=4,column=0)
                

                self.loginframe43 = LabelFrame(self.loginframe4, width =450 , height= 225, bd=0,
                                              font=('Times New Roman', 10,'bold'),bg="gray24", fg="Paleturquoise3")
                self.loginframe43.grid(row=4,column=2)


                #--------Label2--------------------------
                self.lbluser = Label(self.loginframe1, text='Speler 1', font=('Times New Roman', 30,'bold'), bd=22,
                                         bg='gray24', fg='Paleturquoise3')
                self.lbluser.grid(row=0, column=0)

                self.txtuser = Entry(self.loginframe1, width = 33, bd=7, textvariable = self.Username1, font=('Times New Roman', 20,'bold'))
                
                self.txtuser.grid(row=0, column=1, padx=88)
                self.txtuser.focus_set()
                
                self.lbluser2 = Label(self.loginframe1, text='Speler 2', font=('Times New Roman', 30,'bold'), bd=22,
                                         bg='gray24', fg='Paleturquoise3')
                self.lbluser2.grid(row=1, column=0)

                self.txtuser2 = Entry(self.loginframe1, width = 33, bd=7, textvariable = self.Username2, font=('Times New Roman', 20,'bold'))
                self.txtuser2.grid(row=1, column=1, padx=88)
                


                #-------Buttons------------------------------

                self.btnLogin = Button(self.loginframe2, text='LOGIN', width=15, bg='gray24', command=  self.Inlogsystem,
                                       font=('Times New Roman', 25,'bold'),fg='Paleturquoise3')
                self.btnLogin.grid(row=0, column=0)
                
                self.btnReset = Button(self.loginframe2, text='RESET', width=15, bg='gray24', command=self.Resetwindow,
                                       font=('Times New Roman', 25,'bold'),fg='Paleturquoise3')
                self.btnReset.grid(row=0, column=1)
                
                self.btnExit = Button(self.loginframe2, text='EXIT', width=15, bg='gray24', command = self.Exitwindow,
                                       font=('Times New Roman', 25,'bold'),fg='Paleturquoise3')
                self.btnExit.grid(row=0, column=2)
                



                def Algemene_voorwaardenscherm(window):
                        self.algemeenwindow = Toplevel(window)
                        self.Algemeenapp = Algemene_voorwaarden (self.algemeenwindow)
   
                #-----------Label ----------
                self.cmptext = Label(self.window, text= 'Tewolde Company',bg='gray24',anchor= 's', font=('Times New Roman', 18,'bold'),fg='Paleturquoise3')
                self.cmptext.place(relx=0.5, rely=0.94, anchor='s')

                self.cmptext1 = Label(self.window, text= 'EST. 1992',bg='gray24',anchor= 's', font=('Times New Roman', 14,'bold'),fg='Paleturquoise3')
                self.cmptext1.place(relx=0.5, rely=0.97, anchor='s')

                #----------Algemene voorwaarden---------

                self.algemenevoorwaarden1 = Label(self.window
                                       , text= 'Klik',bg='gray24',cursor='hand2', anchor= 'e', font=('Times New Roman', 14,'bold'),fg='Paleturquoise3')
                
                self.algemenevoorwaarden1.place(relx=0.403, rely=1.0, anchor='se')
                
                
                self.algemenevoorwaarden = Label(self.window
                                       , text= 'HIER',bg='gray24',cursor='hand2', anchor= 'e', font=('Times New Roman', 14,'bold'),fg='Paleturquoise3')
                
                self.algemenevoorwaarden.place(relx=0.46, rely=1.0, anchor='se')
                self.algemenevoorwaarden.bind('<Button-1>', lambda event: Algemene_voorwaardenscherm(self.window))
                
                self.f = font.Font(self.algemenevoorwaarden, self.algemenevoorwaarden.cget("font"))
                self.f.configure(underline=True)
                self.algemenevoorwaarden.configure(font=self.f)


                self.algemenevoorwaarden2 = Label(self.window
                                       , text= 'Algemene Voorwaarden',bg='gray24',cursor='hand2', anchor= 'e', font=('Times New Roman', 14,'bold'),fg='Paleturquoise3')
                
                self.algemenevoorwaarden2.place(relx=0.67, rely=1.0, anchor='se')


                #-----------Image-----------

                self.imgWhatsapp = ImageTk.PhotoImage(Image.open("C:\\Users\\ltewo\\AppData\\Local\\Programs\\Python\\Python36\\programmas\\dice rolling simulator\\dobbelstenenjp\\whatsappnieuw.png"))
                self.buttonWhatsapp = Button(self.window,  image=self.imgWhatsapp,  borderwidth =0, anchor='se', command = self.get_whatsapp)
                self.buttonWhatsapp.place(relx=0.1, rely=1.0, anchor='se')
                
                self.imgTwitter = ImageTk.PhotoImage(Image.open("C:\\Users\\ltewo\\AppData\\Local\\Programs\\Python\\Python36\\programmas\\dice rolling simulator\\dobbelstenenjp\\twitter.png"))
                self.browserbutton = Button(self.window, text='twitter', image=self.imgTwitter,borderwidth=0, bd=0, command = self.get_twitter)
                self.browserbutton.place(relx=0.01, rely=1.0, anchor='sw')
                                                    
                self.algemene_voorwaarden = False
                
                
        def Inlogsystem(self):
                
                if self.algemene_voorwaarden == True:
                        
                        user1 = (self.Username1.get())
                        user2 = (self.Username2.get())
                        
                        if user1 != " " and user1 != "" and user2 != " " and user2 != "" and user1 != user2:
                                self.Dobbel2scherm()
                                
                                
                        elif user1 == "" or user1 == " ":
                                tkinter.messagebox.showwarning("Gebruikersnamen", "De gebruikersnaam van Speler 1 is leeg")
                                self.txtuser.focus_set()

                        elif user2 == "" or user2 == " ":
                                tkinter.messagebox.showwarning("Gebruikersnamen", "De gebruikersnaam van Speler 2 is leeg")
                                self.txtuser2.focus_set()       
                                
                        elif user1 == user2:
                                tkinter.messagebox.showwarning("Gebruikersnamen", "De gebruikersnamen mogen niet gelijk aan elkaar zijn")

                else:
                        print('Je hebt de algemene voorwaarden nog niet gelezen')


                
        def speakmessage(self, message):

                self.engine = pyttsx3.init()
                self.voices = self.engine.getProperty('voices')
                self.engine.setProperty('voice', self.voices[1].id)
                self.engine.setProperty('rate', 150)
                self.engine.say('{}'.format(message))
                self.engine.runAndWait()                     
                
                                  

        def Resetwindow(self):
                self.Username1.set("")
                self.Username2.set("")
                


        def Exitwindow(self):

                self.message = "confirm if you want to exit"
                self.speakmessage(self.message)
                self.Exitwindow = tkinter.messagebox.askyesno("EXIT", "confirm if you want to exit", parent=self.window)
                if self.Exitwindow == True:
                        self.window.destroy()
                        return

                
        def Dobbel2scherm(self):
                self.window.destroy()
                self.dobbelwindow  = Tk()
                
                self.Dobbel2scherm = Dobbelsteen(self.dobbelwindow, self.Username1.get(), self.Username2.get())




        def get_twitter(self):
                url = 'https://twitter.com/BrothersTewolde'
                webbrowser.open(url)
                
        def get_whatsapp(self):
                url = 'https://www.whatsapp.com/'
                webbrowser.open(url)


class Algemene_voorwaarden(Dobbelsteeninlog):
        def __init__(self, algemeenwindow):

                #---------Window-----------------------
                self.window = algemeenwindow
                self.window.title("Algemene voorwaarden")
                self.window.geometry("450x450+0+0")
                self.window.config(bg="gray24")
                
                

                self.Algvoorwaarden = LabelFrame(self.window, width = 450, height= 450, bd=20,
                                              font=('Times New Roman', 10,'bold'),bg="gray24", fg="Paleturquoise3")
                
                self.Algvoorwaarden.grid(row=0,column=0)
                
                self.AlgvoorLbl = Label(self.Algvoorwaarden, text='Algemene voorwaarden', font=('Times New Roman', 30,'bold'),bg="gray24", fg="Paleturquoise3")
                self.AlgvoorLbl.grid(row=0,column=0)

                self.AlgvoorwaardTxt = Text(self.window, font=('Times New Roman', 15,'bold'),bg="gray24", height=13, width=30, fg="Paleturquoise3")
                text = 'Algemene voorwaarden.Je moet de voorwaarden lezen voordat je kan spelen.'
                
                self.AlgvoorwaardTxt.insert('1.0',text + '\n')

                self.fontalg = font.Font(self.AlgvoorwaardTxt, self.AlgvoorwaardTxt.cget("font"))
                self.fontalg.configure(underline=True)
                self.AlgvoorwaardTxt.configure(font=self.fontalg)

                self.AlgvoorwaardTxt.grid(row=1, column=0)

                self.AlgBtn = Button(self.window, text='OK',font=('Times New Roman', 10),command = self.start_game_alg)
                self.AlgBtn.grid(row=2,column=0)

        def start_game_alg(self):
                
Reply
#2
If I have read your post correctly you want the user to have access to "play" only if they have read the TOS (Terms Of Service), or your privacy statement and that it would know that they have agreed to the terms... is that correct?

To code that, it might be worth simply making the Privacy or TOS page as Top layer and add a check box in the coding and code the action accordingly.

Example... If the value of the check box is unchecked then the value of the variable for the check box is "0" whereas the button has no command to jump to code and remains null.
If the check box is checked the value then becomes "1" and the command to jump and execute the def to start the game executes.

This would seem to be the easiest way to accomplish what you are after... if I have understand your query correctly.
"Often stumped... But never defeated."
Reply
#3
Dear DT2000,

thank you for your reply.

I wonder how i can connect class 1 (login-system) with class 2 (privacy terms)?

for example:

In class 1 i have defined an attribute called 'self.start_game = False' and in class 2 if the user presses the button 'OK', i want to adjust the value self.start_game in class 1.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can import variable beteen classes in same module johnjh 1 1,912 Apr-19-2020, 09:41 PM
Last Post: deanhystad
  Scope of variable when using two classes AyJay 2 2,133 Jan-23-2020, 10:09 AM
Last Post: AyJay

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020