Cannot get the score to update when using Tkinter

first off function Score() does not return anything

simplest solution would be to make score a global variable and when event occurs do

score += 500

which is the same as score = score + 500 and as text just do score which is the variable and you should make it global

Edited code:

score = 0
class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(MainMenu)

    def switch_frame(self, frame_class):
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()


class MainMenu(tk.Frame):
    def __init__(self, master):
        #Maths Picture/Button
        global photo
        tk.Frame.__init__(self, master)
        photo = PhotoImage(file = "MathsPicture.png")
        photoimage = photo.subsample(3,3)
        tk.Label(self, text="MainMenu", font=('Verdana', 18, "bold")).pack(side="top", fill="x", pady=5)
        tk.Button(self, image = photo, command=lambda: master.switch_frame(PageOne)).pack(side="left")
        tk.Button(self, text="Go to page two",command=lambda:[master.switch_frame(PageTwo), Score()]).pack()
        
def event(event=None):
    global score
    score += 500
    # asign this function to a button or sth

class PageOne(tk.Frame):
    global score
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Frame.configure(self,bg='blue')
        tk.Label(self, text="Page one", font=('Helvetica', 18, "bold")).pack(side="top", fill="x", pady=5)
        tk.Label(self, text=score , font=("Verdana", 18, "bold")).pack(side="bottom")
        tk.Button(self, text="Go back to start page",
                  command=lambda: master.switch_frame(MainMenu)).pack()
        tk.Button(self, text='Update score', command=event)

class PageTwo(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Frame.configure(self,bg='red')
        tk.Label(self, text="Page two", font=('Helvetica', 18, "bold")).pack(side="top", fill="x", pady=5)
        tk.Button(self, text="Go back to start page",
                  command=lambda: master.switch_frame(MainMenu)).pack()
        tk.Button(self, text='Update score', command=event)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top