Python - How to set priority for multiple commands in one button?

Viewed 167

I have created a button to add team member to list, and I want that after the user enters the username and clicks on the "Confirm User" button, the program FIRST checks that the username is entered, and then transfers user to a new frame. I already have a function to check the presence of username and created the following frame, that will arise after pressing this button. but I don’t know how to properly assign them to one button.

My code:

(I'm focusing class TeamsPage(ttk.Frame), confirmBtn now)

from tkinter import *
from tkinter import messagebox
import tkinter.ttk as ttk


class CollegeApp(Tk):
    def __init__(self):
        Tk.__init__(self)
        container = ttk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        self.frames = {}
        for F in (StartPage, selectionPage, TeamsPage, IndividPage, successfullAddTeam):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()


class StartPage(ttk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ttk.Frame.__init__(self, parent)
        self.startMenu()

    def startMenu(self):
        heading = Label(self, text="College Tournament Points\n Count Software",
                        font=('Arial', 25))
        heading.grid(row=0, column=0, columnspan=2, padx=240, pady=40)

        start_Btn = Button(self, text="Start", font="Arial 16", width=8,
                           command=lambda: self.controller.show_frame(selectionPage))
        start_Btn.grid(row=1, column=0, padx=30, pady=5)

        exit_Btn = Button(self, text="EXIT", font="Arial 16", width=8,
                          command=self.controller.destroy)
        exit_Btn.grid(row=1, column=1, padx=30, pady=5)

    def starting_Program(self):
        pass


class selectionPage(ttk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ttk.Frame.__init__(self, parent)
        self.teamOrIndiv()

    def teamOrIndiv(self):
        heading = Label(self, text="Select one of two options",
                        font=('Arial', 25))
        heading.grid(row=0, column=0, columnspan=2, padx=250, pady=40)

        teams = Button(self, text="Teams", font="Arial 24", width=15,
                       command=lambda: self.controller.show_frame(TeamsPage))
        teams.grid(row=1, column=0, padx=270, pady=5)

        individ = Button(self, text="Individuals", font="Arial 24", width=15,
                         command=lambda: self.controller.show_frame(IndividPage))
        individ.grid(row=2, column=0, padx=270, pady=0)


class TeamsPage(ttk.Frame):

    def __init__(self, parent, controller):
        self.controller = controller
        ttk.Frame.__init__(self, parent)
        self.userEntry()

    def userEntry(self):
        headingTest = Label(self, text="Enter your UserName:", font="Arial 20")
        headingTest.grid(row=0, column=0, pady=0)

        self.usernameEnter = Entry(self, width=40)
        self.usernameEnter.grid(row=0, column=1, padx=2, pady=10)

        self.TeamName = StringVar(self)
        self.TeamName.set("Team1")

        AdditionalText = Label(self, text="Please select a team:", font="Arial 18")
        AdditionalText.grid(row=1, column=0, sticky=W, pady=15)
        self.team_names = list(teams.keys())[:-1]
        self.teamSelection = OptionMenu(self, self.TeamName, *self.team_names)
        self.teamSelection.grid(row=1, column=1, sticky=W)

        confirmBtn = Button(self, text="Confirm User", font="Arial 16",
                            command=lambda: [self.add_to_team, self.controller.show_frame(successfullAddTeam)])
        confirmBtn.config(height=4, width=12)
        confirmBtn.grid(row=2, column=2, sticky=E, padx=65, pady=300)

    def add_to_team(self):
        user = self.usernameEnter.get()
        if len(user) == 0:
            messagebox.showwarning(title='No user', message='Please enter a username!')
            return

        team_name = self.TeamName.get()
        team = teams[team_name]

        if user in team:
            messagebox.showwarning(title='In team', message=f'{user} is already a member of {team_name}!')
        if len(team) == 5 and len(teams['Individual']) < 20:
            resp = messagebox.askyesno(title='Team full',
                                       message=f'There are no more spaces in {team_name}!\nDo you want to join the Individual team?')
            print(resp)
            if resp:
                team = teams['Individual']
            else:
                return
        team.add(user)
        print(teams)


class IndividPage(ttk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ttk.Frame.__init__(self, parent)
        self.userEntry()

    def userEntry(self):
        usernameEnter = Entry(self, text="Enter your UserName: ", width=30)
        usernameEnter.grid(row=0, column=0)


class successfullAddTeam(ttk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ttk.Frame.__init__(self, parent)
        self.userEntry()

    def userEntry(self):
        successText = Label(self, text="You have successfully joined to a team!",
                            font="Arial 25")
        successText.grid(row=0, column=0, columnspan=2, padx=180, pady=35)


if __name__ == '__main__':
    teams = {}
    for team in range(1, 5):
        teams[f'Team{team}'] = set()
    teams['Individual'] = set()
    app = CollegeApp()
    app.geometry("800x500")
    app.title('Points Counter')
    app.mainloop()

I tried to use method like this: self.testButton = Button(self, text=" test", command=lambda:[funct1(),funct2()]), but in that case program automatically moves to the next frame without checking Entry Widget and if user will leave it empty, message box will not appear.

1 Answers

The simple solution is to use a proper function rather than a lambda. There's simply no reason to use lambda the way you're using it. A function will be easier to write, easier to debug, and easier to understand.

A good rule of thumb is that a button or binding should always call a function, and lambda should be used only if that function requires a parameter.

class TeamsPage(ttk.Frame):
    ...
    def userEntry(self):
        ...
        confirmBtn = Button(..., command=self.confirm)
        ...

    def confirm(self):
        if self.add_to_team():
            self.controller.show_frame(successfullAddTeam)

    def add_to_team(self):
        ...
        if <add was successful>:
            return True
        else
            return False
Related