def make_entry(self): """construct of Entry Parameters ---------- None Returns ------- None """ vcmd = self.lf0.register(self.is_okay) ent0 = Entry(self.lf0, validatecommand=(vcmd, '%P', '%S', '%i'), validate='key', textvariable=self.out_var) ent0.bind("<Return>", self.end_input) ent0.grid(row=1, column=0, padx=10) ent0.focus()
def frame_inputs(root): frame = Frame(root, **padded) # type: ignore # Configure grid frame.rowconfigure(0, weight=1) frame.rowconfigure(1, weight=1) frame.columnconfigure(0, weight=1) frame.columnconfigure(1, weight=1) frame.columnconfigure(2, weight=1) # Place widgets entry = Entry(frame, width=7, textvariable=self.feet) entry.grid(column=1, row=0) entry.focus() label = Label(frame, text="feet") label.grid(column=2, row=0) label = Label(frame, text="is equivalent to") label.grid(column=0, row=1) label = Label(frame, text="meters") label.grid(column=2, row=1) label = Label(frame, textvariable=self.meters) label.grid(column=1, row=1) return frame
class Program(Frame): """Class to represent a main window""" def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.meters_value = StringVar() self.initUI() def initUI(self): self.grid(column=0, row=0, sticky=(N, W, E, S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.parent.title('Feet to meter') self.pack(expand=True) self.centerWindow() self.initItems() def initItems(self): """Initialize all widgets here""" # An entry to enter feet value. self.feet_entry = Entry(self, width=7) self.feet_entry.grid(column=2, row=1, sticky=(W, E)) # A label to display translated meters. self.meters_lbl = Label(self, textvariable=self.meters_value) self.meters_value.set(0) self.meters_lbl.grid(column=2, row=2, sticky=(W, E)) # Different labels for text only. Label(self, text='feet').grid(column=3, row=1, sticky=W) Label(self, text='is equivalent to').grid(column=1, row=2, sticky=E) Label(self, text='meters').grid(column=3, row=2, sticky=W) # Button to calculate things. calc_btn = Button(self, text='Calculate', command=lambda: calculate(self)) calc_btn.grid(column=3, row=3, sticky=W) # This widget is just for fun. # Also it shows how to get an event callback when Entry widget is modified def callback(str): print(str.get()) entry_str = StringVar() entry_str.trace('w', lambda name, index, mode, str=entry_str: callback(str)) self.entry_widg = Entry(self, width=10, textvariable=entry_str) self.entry_widg.grid(column=1, row=4, sticky=(W, E)) # A really simple way to change label text: test_lbl = Label(self) test_lbl.grid(column=3, row=4, sticky=E) test_lbl['text'] = 'hello!' # Handling label's events ev_lbl = Label(self, text='Do something with me...', width=30) ev_lbl.grid(column=1, row=5, columnspan=2, rowspan=2) ev_lbl.bind('<Enter>', lambda e: ev_lbl.configure(text='Moved mouse inside')) ev_lbl.bind('<Leave>', lambda e: ev_lbl.configure(text='Moved mouse outside')) ev_lbl.bind( '<1>', lambda e: ev_lbl.configure(text='Clicked left mouse button!')) ev_lbl.bind( '<Double-1>', lambda e: ev_lbl.configure( text='Double clicked left mouse button!')) # Configure pads for all grid cells for child in self.winfo_children(): child.grid_configure(padx=5, pady=5) # As default, entry is focused self.feet_entry.focus() def centerWindow(self): """Place the main window in the center of screen""" window_w = 300 window_h = 200 screen_w = self.winfo_screenwidth() screen_h = self.winfo_screenheight() x = (screen_w - window_w) / 2 y = (screen_h - window_h) / 2 self.parent.geometry('%dx%d+%d+%d' % (window_w, window_h, x, y))
def init(metrics_data: dict): top_window = Tk() # main widget properties top_window.geometry(f'{metrics_data["width"]}x{metrics_data["height"]}') top_window.iconphoto(False, PhotoImage(file=f'../{metrics_data["icon"]}')) top_window.configure(bg=metrics_data['background']) top_window.title(metrics_data['title']) def play(track_path: str, duration: int) -> None: playsound(track_path, False) top_window.after(duration * 1000, lambda: play(track_path, duration)) def pick_directory(): # TODO: set $HOME directory as default (may be in config) path_save = filedialog.askdirectory().strip() if path_save: input_directory.delete(0, END) input_directory.insert(0, path_save) def make_request(): author: str = input_author.get().strip() path_save: str = input_directory.get().strip() if not author.strip(): messagebox.showerror('🚫 Error occurred!', 'Empty string is not allowed as author\'s name.') return 1 # directory to save should be present -- chosen or default print('author:', author) print('directory to save:', path_save) pass def close(): top_window.destroy() top_window.quit() # UI label_guide = Label(top_window, text=metrics_data['guide'], font=('Arial Bold', 23)) label_guide.grid(column=0, row=0, padx=(14, 5), pady=(20, 50)) input_author = Entry(top_window, width=50) input_author.grid(row=8, column=0) input_author.focus() input_directory = Entry(top_window, width=50) input_directory.grid(row=9, column=0) button_choose = Button(top_window, text='Choose', command=pick_directory) button_choose.grid(row=9, column=1) Separator(orient='horizontal') button_go = Button(top_window, text='Go!', command=make_request) button_go.grid(row=10, column=0) top_window.protocol('WM_DELETE_WINDOW', close) play(f'../{metrics_data["track"]}', 83) top_window.mainloop()
class Register(Frame): def __init__(self, master): super().__init__(master=master) self.layout_components() # Setup Callbacks self.show_sign_in: Callable = None self.sign_in: Callable = None self.search_email: Callable = None self.search_username: Callable = None self.search_password: Callable = None self.register: Callable = None self.username_valid: bool = False self.email_valid: bool = False self.password_valid: bool = False self.passcnfm_valid: bool = False # Refocus to Email Entry self.email_Entry.focus() def layout_components(self): self.pack(fill=tk.BOTH, expand=False, padx=PADX, pady=PADY) error_font = font.Font(family="Ariel", size=8) # Variables self.username = tk.StringVar() self.username.set("") self.email = tk.StringVar() self.email.set("") self.password = tk.StringVar() self.password.set("") self.passcnfm = tk.StringVar() self.passcnfm.set("") # Email Row email_Frame = Frame(self) email_Frame.pack(fill=tk.X) email_Label = Label(email_Frame, text="Email:", width=LABEL_WIDTH) email_Label.pack(side=tk.LEFT, padx=PADX, pady=PADY) self.email_Entry = Entry(email_Frame, width=ENTRY_WIDTH, textvariable=self.email) self.email_Entry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True) self.email_Entry.bind("<FocusOut>", self._validate_email) # Email Error Row email_errFrame = Frame(self) email_errFrame.pack(fill=tk.X) self.email_errLabel = Label(email_errFrame, text="", foreground="red", font=error_font) self.email_errLabel.pack(side=tk.LEFT, anchor="center", expand=True, padx=PADX, pady=PADY) # Username Row user_Frame = Frame(self) user_Frame.pack(fill=tk.X) user_Label = Label(user_Frame, text="Username:"******"<FocusOut>", self._validate_username) # Username Error Row user_errFrame = Frame(self) user_errFrame.pack(fill=tk.X) self.user_errLabel = Label(user_errFrame, text="", foreground="red", font=error_font) self.user_errLabel.pack(side=tk.LEFT, anchor="center", expand=True, padx=PADX, pady=PADY) # Original Password Row pass_Frame = Frame(self) pass_Frame.pack(fill=tk.X) pass_Label = Label(pass_Frame, text="Password:"******"*") self.pass_Entry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True) self.pass_Entry.bind("<FocusOut>", self._validate_password) # Confirming Password Row pass_cnfmFrame = Frame(self) pass_cnfmFrame.pack(fill=tk.X) pass_cnfmLabel = Label(pass_cnfmFrame, text="Confirm:", width=LABEL_WIDTH) pass_cnfmLabel.pack(side=tk.LEFT, padx=PADX, pady=PADY) self.pass_cnfmEntry = Entry(pass_cnfmFrame, width=ENTRY_WIDTH, textvariable=self.passcnfm, show="*") self.pass_cnfmEntry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True) self.pass_cnfmEntry.bind("<FocusOut>", self._validate_password) # Password Error Row pass_errFrame = Frame(self) pass_errFrame.pack(fill=tk.X) self.pass_errLabel = Label(pass_errFrame, text="", foreground="red", font=error_font) self.pass_errLabel.pack(side=tk.LEFT, anchor="center", expand=True, padx=PADX, pady=PADY) # Button Row button_Frame = Frame(self) button_Frame.pack(fill=tk.X) # Cancel Button cncl_Button = Button(button_Frame, text="Cancel", command=self.cancel) cncl_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False) # Register Button self.register_Button = Button(button_Frame, text="Register", state="disabled", command=self._register) self.register_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False) # View Password Button self.view_pass_Button = Button(button_Frame, text="View Password", command=self.view_password) self.view_pass_Button.pack(side=tk.LEFT, padx=PADX, pady=PADY) # Go Back Button Row gbck_Frame = Frame(self) gbck_Frame.pack(fill=tk.X) gbck_Label = Label(gbck_Frame, text="Have an Account? Go Ahead and ") gbck_Label.pack(side=tk.LEFT, padx=PADX, pady=PADY, expand=False) gbck_Button = Button(gbck_Frame, text="Sign In", command=self._show_sign_in) gbck_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False) def cancel(self): self.email.set("") self.username.set("") self.password.set("") self.passcnfm.set("") self.email_Entry.focus() self.email_errLabel.configure(text="") self.user_errLabel.configure(text="") self.pass_errLabel.configure(text="") def view_password(self): self.pass_Entry.configure(show="") self.pass_cnfmEntry.configure(show="") self.view_pass_Button.configure(text="Hide Password", command=self.hide_password) def hide_password(self): self.pass_Entry.configure(show="*") self.pass_cnfmEntry.configure(show="*") self.view_pass_Button.configure(text="View Passwrod", command=self.view_password) def _show_sign_in(self): if self.show_sign_in is not None: self.show_sign_in() self.cancel() def _register(self): if self.register is not None: self.register() def _validate_email(self, event): email = self.email.get() if len(email) == 0: self.email_errLabel.configure(text="Email Must not be Empty...") self.email_valid = False elif not validate_email(email): self.email_errLabel.configure(text="Email Format Invalide...") self.email_valid = False elif self.search_email is not None and not self.search_email(email): self.email_errLabel.configure(text="Email Already Registered...") self.email_valid = False else: self.email_errLabel.configure(text="") self.email_valid = True self.enable_register() def _validate_username(self, event): username = self.username.get() if len(username) == 0: self.user_errLabel.configure(text="Username Must not be Empty...") self.username_valid = False elif self.search_username is not None and not self.search_username( username): self.username_valid = False else: self.user_errLabel.configure(text="") self.username_valid = True self.enable_register() def _validate_password(self, event): password = self.password.get() passcnfm = self.passcnfm.get() if len(password) == 0: self.pass_errLabel.configure(text="Password Must Not be Empty...") self.password_valid = False elif len(password) < 8: self.pass_errLabel.configure( text="Password Must be Longer than 8 Characters...") self.password_valid = False elif password != passcnfm: self.pass_errLabel.configure(text="Password Must Match... ") self.passcnfm_valid = False elif self.search_password is not None and not self.search_password( password): self.pass_errLabel.configure(text="") self.password_valid = False else: self.pass_errLabel.configure(text="") self.passcnfm_valid = True self.password_valid = True self.enable_register() def enable_register(self): if (self.email_valid and self.username_valid and self.password_valid and self.passcnfm_valid): self.register_Button.configure(state="normal") def failed_register(self): self.email.set("") self.username.set("") self.pass_errLabel.configure(text="Email or Username Already used") self.email_Entry.focus()
def entry_float(parent, lf_text, l_limit, u_limit, mess_text, out_var): """Float layout for entry Parameters ---------- parent : str parent handle lf_text : str text on LabelFrame l_limit : float lower limit u_limit : float upper limit mess_text : str message out_var : float tkvar handle Returns ------- float """ st1 = Style() st1.theme_use('default') st1.configure('brown.TLabelframe', background='#C9B99B') st1.configure('brown.TLabelframe.Label', background='#EDEF77') st1.configure('brown.TLabel', background='#EDEF77') st1.configure('lowr.TLabel', background='lightblue') st1.configure('upr.TLabel', background='red') lf0 = Labelframe(parent, text=lf_text, style='brown.TLabelframe') lf0.grid(row=0, column=0, padx=10, pady=10) ulab = Label(lf0, text=str(u_limit) + " upper limit", style='brown.TLabel') ulab.grid(row=0, column=1, padx=10) llab = Label(lf0, text=str(l_limit) + " lower limit", style='brown.TLabel') llab.grid(row=2, column=1, padx=10) def end_input(_evt): """limit on float Parameters ---------- evt : str bind handle Returns ------- None """ ulab['style'] = 'brown.TLabel' llab['style'] = 'brown.TLabel' if l_limit < entsv.get() < u_limit: messlbl['text'] = "That's OK" out_var.set(entsv.get()) elif l_limit >= entsv.get(): messlbl['text'] = "Input below lower limit" llab['style'] = 'lowr.TLabel' else: messlbl['text'] = "Input above upper limit" ulab['style'] = 'upr.TLabel' def is_okay(text): """ validation function Parameters ---------- text : str text if allowed Returns ------- boolean """ if text in ("", "-", ".", "-."): return True try: float(text) except ValueError: return False return True vcmd = lf0.register(is_okay) entsv = DoubleVar() ent0 = Entry(lf0, validate='key', validatecommand=(vcmd, '%P'), textvariable=entsv) ent0.bind("<Return>", end_input) ent0.grid(row=1, column=0, padx=10) ent0.focus() messlbl = Label(lf0, text=mess_text, style='brown.TLabel') messlbl.grid(row=2, column=0, pady=10, padx=10)
class MainApplication(Frame): def __init__(self, master): self.master = master tabControl = Notebook(self.master) self.tab1 = Frame(tabControl) tabControl.add(self.tab1, text='501') #tabControl.pack(expand=1, fill="both") tab2 = Frame(tabControl) tabControl.add(tab2, text='Round The Board') tabControl.pack(expand=1, fill="both") self.configure_gui() self.create_widgets() self.start_window() def configure_gui(self): self.master.title("501") self.master.geometry("600x500") # function binding return key to entry box self.master.bind('<Return>', lambda e: self.score_Entered()) #create frames self.labFrame1 = LabelFrame(self.tab1, text="Player1 Stats") self.labFrame2 = LabelFrame(self.tab1, text="Player2 Stats") self.labFrame3 = LabelFrame(self.tab1, text="Player1 Scores") self.labFrame4 = LabelFrame(self.tab1, text="Player2 Scores") self.labFrame5 = LabelFrame(self.tab1, text="Enter Scores") #self.labFrame6 = LabelFrame(self.master, text="Additional info") #make frames vis(ible self.labFrame1.grid(row=0, column=0, rowspan=2, sticky='ns') self.labFrame3.grid(row=0, column=1) self.labFrame4.grid(row=0, column=2) self.labFrame2.grid(row=0, column=3, rowspan=2, sticky='ns') self.labFrame5.grid(row=1, column=1, columnspan=2, sticky='ew') #self.labFrame6.grid(row=3, column=1, columnspan=2, sticky='ew') def create_widgets(self): self.pl1name = StringVar() self.pl2name = StringVar() self.pl1sets = StringVar() self.pl1legs = StringVar() self.pl160 = StringVar() self.pl180 = StringVar() self.pl1100 = StringVar() self.pl1140 = StringVar() self.pl1180 = StringVar() self.pl1avg = StringVar() self.pl1chtpc = StringVar() self.pl1chtnumbs = StringVar() #player to go boolean self.player1_togo = True #frame 1 widgets Label(self.labFrame1, text="Totals").grid(row=0, column=0, sticky='w') Label(self.labFrame1, text="Sets:").grid(row=1, column=0, sticky='w') Label(self.labFrame1, textvariable=self.pl1sets).grid(row=1, column=1) Label(self.labFrame1, text="Legs:").grid(row=2, column=0, sticky='w') Label(self.labFrame1, textvariable=self.pl1legs).grid(row=2, column=1) Label(self.labFrame1, text="60+:").grid(row=3, column=0, sticky='w') Label(self.labFrame1, textvariable=self.pl160).grid(row=3, column=1) Label(self.labFrame1, text="80+:").grid(row=4, column=0, sticky='w') Label(self.labFrame1, textvariable=self.pl180).grid(row=4, column=1) Label(self.labFrame1, text="100+:").grid(row=5, column=0, sticky='w') Label(self.labFrame1, textvariable=self.pl1100).grid(row=5, column=1) Label(self.labFrame1, text="140+:").grid(row=6, column=0, sticky='w') Label(self.labFrame1, textvariable=self.pl1140).grid(row=6, column=1) Label(self.labFrame1, text="180:").grid(row=7, column=0, sticky='w') Label(self.labFrame1, textvariable=self.pl1180).grid(row=7, column=1) Label(self.labFrame1, text="Averages").grid(row=8, column=0, sticky='w') Label(self.labFrame1, text="Score:").grid(row=9, column=0, sticky='w') Label(self.labFrame1, textvariable=self.pl1avg).grid(row=9, column=1) Label(self.labFrame1, text="Checkout %:").grid(row=10, column=0, sticky='w') Label(self.labFrame1, textvariable=self.pl1chtpc).grid(row=10, column=1) Label(self.labFrame1, text="Checkout Hit/Thrown:").grid(row=11, column=0, sticky='w') Label(self.labFrame1, textvariable=self.pl1chtnumbs).grid(row=11, column=1) self.pl2sets = StringVar() self.pl2legs = StringVar() self.pl260 = StringVar() self.pl280 = StringVar() self.pl2100 = StringVar() self.pl2140 = StringVar() self.pl2180 = StringVar() self.pl2avg = StringVar() self.pl2chtpc = StringVar() self.pl2chtnumbs = StringVar() #frame 2 widgets Label(self.labFrame2, text="Totals").grid(row=0, column=0, sticky='w') Label(self.labFrame2, text="Sets:").grid(row=1, column=0, sticky='w') Label(self.labFrame2, textvariable=self.pl2sets).grid(row=1, column=1) Label(self.labFrame2, text="Legs:").grid(row=2, column=0, sticky='w') Label(self.labFrame2, textvariable=self.pl2legs).grid(row=2, column=1) Label(self.labFrame2, text="60+:").grid(row=3, column=0, sticky='w') Label(self.labFrame2, textvariable=self.pl260).grid(row=3, column=1) Label(self.labFrame2, text="80+:").grid(row=4, column=0, sticky='w') Label(self.labFrame2, textvariable=self.pl280).grid(row=4, column=1) Label(self.labFrame2, text="100+:").grid(row=5, column=0, sticky='w') Label(self.labFrame2, textvariable=self.pl2100).grid(row=5, column=1) Label(self.labFrame2, text="140+:").grid(row=6, column=0, sticky='w') Label(self.labFrame2, textvariable=self.pl2140).grid(row=6, column=1) Label(self.labFrame2, text="180:").grid(row=7, column=0, sticky='w') Label(self.labFrame2, textvariable=self.pl2180).grid(row=7, column=1) Label(self.labFrame2, text="Averages").grid(row=8, column=0, sticky='w') Label(self.labFrame2, text="Score:").grid(row=9, column=0, sticky='w') Label(self.labFrame2, textvariable=self.pl2avg).grid(row=9, column=1) Label(self.labFrame2, text="Checkout %:").grid(row=10, column=0, sticky='w') Label(self.labFrame2, textvariable=self.pl2chtpc).grid(row=10, column=1) Label(self.labFrame2, text="Checkout Hit/Thrown:").grid(row=11, column=0, sticky='w') Label(self.labFrame2, textvariable=self.pl2chtnumbs).grid(row=11, column=1) #frame 3 widgets self.pl1remaining = StringVar() Label(self.labFrame3, text="Player:").grid(row=0, column=0) Label(self.labFrame3, textvariable=self.pl1name).grid(row=0, column=1) Label(self.labFrame3).grid(row=1) Label(self.labFrame3, text="Remaining").grid(row=2, column=0, columnspan=2, sticky='ew') self.remlabel1 = Label(self.labFrame3, textvariable=self.pl1remaining) self.remlabel1.grid(row=3, column=0, columnspan=2) self.remlabel1.configure(width=3, background='white', font=(None, 35)) #self.pl1remaining.set(self.pl1dict['score']) #self.pl1name.set(game_state.player1) #frame 4 widgets self.pl2remaining = StringVar() Label(self.labFrame4, text="Player:").grid(row=0, column=0) Label(self.labFrame4, textvariable=self.pl2name).grid(row=0, column=1) Label(self.labFrame4).grid(row=1) Label(self.labFrame4, text="Remaining").grid(row=2, column=0, columnspan=2, sticky='ew') self.remlabel2 = Label(self.labFrame4, textvariable=self.pl2remaining) self.remlabel2.grid(row=3, column=0, columnspan=2) self.remlabel2.configure(width=3, background='white', font=(None, 35)) #self.pl2remaining.set(self.pl2dict['score']) #self.pl2name.set(game_state.player2) #frame 5 widgets self.playertogo = StringVar() self.scoreEntered = StringVar() Label(self.labFrame5, text=" ").grid(row=0, column=0) #Label(labFrame5).grid(row=0, column=1) #Label(labFrame5).grid(row=0, column=2) Label(self.labFrame5, text="To Go:").grid(row=1, column=1) playerLabel = Label(self.labFrame5, textvariable=self.playertogo) playerLabel.grid(row=2, column=1) playerLabel.configure(font=(None, 20)) self.number_entry = Entry(self.labFrame5, textvariable=self.scoreEntered, width=5) self.number_entry.grid(row=2, column=2) self.number_entry.configure(background='white', font=(None, 20)) self.number_entry.focus() def start_window(self): self.startWindow = Toplevel(self.master) self.ply1entry = StringVar() self.ply2entry = StringVar() self.setsentry = StringVar() self.legsentry = StringVar() self.ply1Label = Label(self.startWindow, text="Player 1:") self.ply1Label.grid(row=3, column=3) self.ply1Entry = Entry(self.startWindow, textvariable=self.ply1entry, width=10) self.ply1Entry.grid(row=3, column=4, sticky='e') self.ply2Label = Label(self.startWindow, text="Player 2:") self.ply2Label.grid(row=4, column=3) self.ply2Entry = Entry(self.startWindow, textvariable=self.ply2entry, width=10) self.ply2Entry.grid(row=4, column=4, sticky='e') self.setsLabel = Label(self.startWindow, text="Number of Sets:") self.setsLabel.grid(row=5, column=3) self.setsBox = Combobox(self.startWindow, textvariable=self.setsentry, width=5) self.setsBox['values'] = (1, 3, 5, 7, 9) self.setsBox.current(1) self.setsBox.grid(row=5, column=4) self.legsLabel = Label(self.startWindow, text="Number of Legs:") self.legsLabel.grid(row=6, column=3) self.legsBox = Combobox(self.startWindow, textvariable=self.legsentry, width=5) self.legsBox['values'] = (1, 3, 5, 7, 9) self.legsBox.current(2) self.legsBox.grid(row=6, column=4) self.plyButton = Button(self.startWindow, text="Start Game", command=self.fiveohone_start) self.plyButton.grid(row=7, column=4) root.wait_window(self.startWindow) def fiveohone_start(self): player1name = self.ply1entry.get() player2name = self.ply2entry.get() numbersets = int(self.setsentry.get()) numberlegs = int(self.legsentry.get()) self.startWindow.destroy() def stats_update(self, player1, player2): self.pl1sets.set(player1.stats['sets']) self.pl1legs.set(player1.stats['legs']) self.pl1remaining.set(player1.stats['score']) self.pl160.set(player1.stats['60+']) self.pl180.set(player1.stats['80+']) self.pl1100.set(player1.stats['100+']) self.pl1140.set(player1.stats['140+']) self.pl1180.set(player1.stats['180']) numbset = ( "%s / %s" % (player1.stats['dartsatdoubles'], player1.stats['doubleshit'])) self.pl1chtnumbs.set(numbset) average1 = (player1.stats['totalScore'] / player1.stats['numberDarts']) * 3 average1 = round(average1, 2) self.pl1avg.set(average1) #self.remlabel1.configure(background='yellow') #self.playertogo.set(self.player1name) self.pl2sets.set(player2.stats['sets']) self.pl2legs.set(player2.stats['legs']) self.pl2remaining.set(player2.stats['score']) self.pl260.set(player2.stats['60+']) self.pl280.set(player2.stats['80+']) self.pl2100.set(player2.stats['100+']) self.pl2140.set(player2.stats['140+']) self.pl2180.set(player2.stats['180']) self.pl2avg.set(player2.stats['avg']) numbset2 = ( "%s / %s" % (player2.stats['dartsatdoubles'], player2.stats['doubleshit'])) self.pl2chtnumbs.set(numbset2) average2 = (player2.stats['totalScore'] / player2.stats['numberDarts']) * 3 average2 = round(average2, 2) self.pl2avg.set(average2) self.counter += 1 def who_starts(self, sets, legs): if sets % 2 != 0: if legs % 2 != 0: self.playertogo.set(self.player1name) self.remlabel1.configure(background='yellow') self.remlabel2.configure(background='white') game_state.playertogo = 1 else: self.playertogo.set(self.player2name) self.remlabel2.configure(background='yellow') self.remlabel1.configure(background='white') game_state.playertogo = 2 def score_Entered(self): if self.counter == 1: player1.stats['totalScore'] = 0 player1.stats['numberDarts'] = 0 elif self.counter == 2: player2.stats['totalScore'] = 0 player2.stats['numberDarts'] = 0 self.score = int(self.scoreEntered.get()) if game_state.playertogo == 1: player1.stats['score'] -= self.score player1.stats['totalScore'] += self.score player1.stats['numberDarts'] += 3 player1.status(self.score, player1) self.stats_update(player1, player2) self.playertogo.set(self.player2name) self.remlabel2.configure(background='yellow') self.remlabel1.configure(background='white') if (player1.stats['score'] > 0) and (player1.stats['score'] < 50): darts_at_double = Toplevel() self.doubleDarts = Combobox(darts_at_double, width=5, textvariable=self.dartsatdouble) self.doubleDarts.bind("<<ComboboxSelected>>", self.darts_at_double) self.doubleDarts['values'] = ('1', '2', '3') self.doubleDarts.grid(row=1, column=1) main_app.wait_window(darts_at_double) #self.doubleDarts.grid() #self.doubleDarts_label.grid() self.number_entry.delete(0, END) game_state.playertogo = 2 else: player2.stats['score'] -= self.score player2.stats['totalScore'] += self.score player2.stats['numberDarts'] += 3 player2.status(self.score, player2) self.stats_update(player1, player2) self.playertogo.set(self.player1name) self.remlabel1.configure(background='yellow') self.remlabel2.configure(background='white') self.number_entry.delete(0, END) game_state.playertogo = 1 def darts_at_double(self, player): self.darts_at_doubles = int(self.dartsatdouble.get()) if game_state.playertogo == 2: player1.stats['dartsatdoubles'] += self.darts_at_doubles self.stats_update(player1, player2) self.doubleDarts.grid_remove() self.doubleDarts_label.grid_remove() def leg_won_darts(self): pass
class ClientSetUp(Frame): """ Dialog box that presents 3 inputs to the user: Username Server IP Port Extends the Frame class in tkinter. """ def __init__(self): super().__init__() self.name = '' self.ip = '' self.port = '' self.initUI() def initUI(self): """ Initialises the dialog box. The box will contain fields for the username, server ip and server port. A button is used to submit the data. """ self.master.title("Connection Details") self.pack(fill=BOTH, expand=True) # Prepare the username field frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text="Username", width=14) lbl1.pack(side=LEFT, padx=5, pady=10) self.entry1 = Entry(frame1, textvariable=self.name) self.entry1.pack(fill=X, padx=5, expand=True) # Prepare the server address field frame2 = Frame(self) frame2.pack(fill=X) lbl2 = Label(frame2, text="Server Address", width=14) lbl2.pack(side=LEFT, padx=5, pady=10) self.entry2 = Entry(frame2, textvariable=self.ip) self.entry2.pack(fill=X, padx=5, expand=True) # Prepare the server port field frame3 = Frame(self) frame3.pack(fill=X) lbl3 = Label(frame3, text="Server Port", width=14) lbl3.pack(side=LEFT, padx=5, pady=10) self.entry3 = Entry(frame3, textvariable=self.port) self.entry3.pack(fill=X, padx=5, expand=True) frame4 = Frame(self) frame4.pack(fill=X) # Command tells the form what to do when the button is clicked btn = Button(frame4, text="Submit", command=self.onSubmit) btn.pack(padx=5, pady=10) # Give entry1 focus self.entry1.focus() # Set up what happens when Return is pressed # All entries will move onto the next except port which will submit # Note: These didn't work if they weren't lambdas (don't know why) self.entry1.bind('<Return>', lambda event: self.entry2.focus()) self.entry2.bind('<Return>', lambda event: self.entry3.focus()) self.entry3.bind('<Return>', lambda event: self.onSubmit()) photo = PhotoImage(file=resource_path('icon.png')) self.master.iconphoto(False, photo) def onSubmit(self): """ When clicked, the user input is stored in the instance variables and the boxes are cleared. The widget is then destroyed. """ self.name = self.entry1.get() self.ip = self.entry2.get() self.port = self.entry3.get() self.entry1.delete(0, END) self.entry2.delete(0, END) self.entry3.delete(0, END) self.quit() def retry(self, name='', ip='', port=''): """ Used if the user enters incorrect data. It will repopulate the fields where the data was correct. The mainloop is started once the fields are populated. Parameters: name (str): Name of client ip (str): IP of server port (str): Port of server """ self.entry1.insert(0, name) self.entry2.insert(0, ip) self.entry3.insert(0, port) self.mainloop() self.quit() def on_close(self): self.destroy() sys.exit()
class MemberChecker(PanedWindow): def __init__(self, parent): PanedWindow.__init__(self, parent, background="white") self.parent = parent self.init_data() self.init_log() self.init_ui() self.update_status() def init_data(self): self.data_store = api.DataStore() def init_log(self): self.entrance_log = entrance_log.EntranceLog() def init_ui(self): self.parent.title("Member Checker") self.columnconfigure(3, weight=3) self.pack(fill=BOTH, expand=True) self.input = StringVar() self.input_entry = Entry(self, textvariable=self.input) self.input_entry.bind('<Return>', self.submit) self.input_entry.grid(row=0, column=0, columnspan=3, sticky=E + W) self.result = StringVar() self.result_label = Label(self, textvariable=self.result) self.result_label.grid(row=3, column=0, columnspan=3, sticky=E + W) self.name = StringVar() name_label = Label(self, textvariable=self.name) name_label.grid(row=2, column=0, columnspan=3, sticky=E + W) self.status = StringVar() status_label = Label(self, textvariable=self.status) status_label.grid(row=4, column=0, columnspan=4, sticky=E + W) submit_button = Button(self, text="Submit", command=self.submit) submit_button.grid(row=1, column=2) enter_without_card_button = Button(self, text="Enter without card", command=self.enter_without_card) enter_without_card_button.grid(row=1, column=0) enter_member_without_card_button = Button(self, text="Enter member without card", command=self.enter_member_without_card) enter_member_without_card_button.grid(row=1, column=1) self.entrance_log_list = Listbox(self) self.entrance_log_list.grid(row=0, column=3, rowspan=4, sticky=E + W + S + N) self.input_entry.focus() def load_data(self): if messagebox.askyesno("Load new API Data", "Are you sure you want to load the new API data? All previous data will be removed. The program might be unresponsive for a few seconds, but don't kill it, please! It has feelings too."): self.data_store.load_api_data() def enter_by_identification(self, identification): member = self.data_store.find_member_by_identification(identification) if member is None: if messagebox.askyesno("Not a member", "This university identification is not registered as a member. Do you want to let them in as a non-member?"): self.enter_non_member_by_identification(identification) else: self.enter_member(member) def enter_by_barcode(self, barcode): member = self.data_store.find_member_by_barcode(barcode) if member is None: if messagebox.askyesno("Not a member", "This barcode is not registered as a member. Do you want to let them in as a non-member?"): self.enter_non_member_by_barcode(barcode) else: self.enter_member(member) def enter_non_member_by_identification(self, identification): self.entrance_log.enter_non_member_by_identification(identification) self.enter_non_member() def enter_non_member_by_barcode(self, barcode): self.entrance_log.enter_non_member_by_barcode(barcode) self.enter_non_member() def enter_without_card(self): self.clear_result() self.entrance_log.enter_without_card() self.enter_non_member() self.input_entry.focus() def enter_member(self, member): inside_result = self.entrance_log.is_member_inside(member) if inside_result[0]: if not messagebox.askyesno("Already inside", "This membership card has already been used to enter at {}. Are you sure you want to register it again? Normally you should let this person enter without card (and bill them accordingly).".format( inside_result[1])): return self.entrance_log.enter_member(member) self.result.set('Member!') self.result_label.configure(background='green') self.name.set(member['firstName'] + ' ' + member['lastName']) self.update_status() def enter_non_member(self): self.result.set('Not a member!') self.result_label.configure(background='red') self.name.set('Not in the database') self.update_status() def enter_member_without_card(self): name = self.input.get() if len(name) == 0: messagebox.showinfo('Name required', 'Please enter the name of this person!') return self.entrance_log.enter_member_without_card(name) self.result.set('Member without card!') self.result_label.configure(background="orange") self.name.set('') self.input.set('') self.update_status() def clear_result(self): self.result.set('') self.result_label.configure(background='white') self.name.set('') def submit(self, event=None): self.clear_result() entry = self.input.get() if helpers.is_valid_identification(entry): self.enter_by_identification(entry) elif helpers.is_valid_barcode(entry): self.enter_by_barcode(entry) else: messagebox.showinfo('Invalid entry', 'The data entered was not recognized as a valid bar code or a valid university identification. You should click \'enter without card\' to let this person in.') return self.input.set('') self.input_entry.focus() def clear_log(self): if messagebox.askyesno("Clear log", "Are you sure you want to clear the log of all people who entered?"): self.entrance_log.clear_log() self.update_status() def update_status(self): self.status.set("{} members inside. Total: {}".format(self.entrance_log.members_inside_count(), self.entrance_log.inside_count())) logs = self.entrance_log.get_latest_logs(15) self.entrance_log_list.delete(0, 15) for l in logs: s = l['timestamp'] + ": " data = l['data'] if 'member_id' in data: member = self.data_store.find_member(data['member_id']) s += member['firstName'] + " " + member['lastName'] elif 'barcode' in data: s += data['barcode'] elif 'identification' in data: s += data['identification'] elif 'name' in data: s += '[no card]' + data['name'] else: s += "-" self.entrance_log_list.insert(0, s)
class SettingsUI: def __init__(self, mainFrame): "initiates settings and creates the interface" self.playerList = [] self.gameList = ("301", "501", "Clock") self.initUI(mainFrame) def buildPlayerHeaderString(self): """Build a connection string from a dictionary of parameters. Returns string.""" return "Players: " + ", ".join(["%s" % player.name for player in self.playerList]) def addPlayerText(self, name): self.playerList.append(Player(name)) #bind add player click event def onAddPlayerClick(self, event): "callback method for the add player button" self.addPlayer() def onAddPlayerEnter(self, event): "callback method for the add player button" if event.keycode == 13: self.addPlayer() def addPlayer(self): name = self.playerNameEntry.get() if name: self.addPlayerText(name) self.playerString.set(self.buildPlayerHeaderString()) self.nameFieldVar.set("") self.playerNameEntry.focus() return("break") def initUI(self, mainFrame): """initialize the User Interface""" # styles style = Style() style.configure("GRN.TLabel", background="#ACF059") style.configure("GRN.TFrame", background="#ACF059") style.configure("BLK.TFrame", background="#595959") # create top frame topFrame = Frame(mainFrame, style="GRN.TFrame", padding=8) topFrame.pack(fill=BOTH, side=TOP) # create black border borderFrame = Frame(mainFrame, style="BLK.TFrame") borderFrame.pack(fill=BOTH, side=TOP) # create add player frame addPlayerFrame = Frame(mainFrame, padding=8) addPlayerFrame.pack(side=TOP) # create text field for add button self.nameFieldVar = StringVar() self.playerNameEntry = Entry(addPlayerFrame, textvariable = self.nameFieldVar) self.playerNameEntry.pack(side=LEFT) # create add player button addButton = Button(addPlayerFrame, text="Add player") addButton.pack(side=LEFT) # create choose game list self.currentGame = StringVar() self.currentGame.set(self.gameList[0]) gameDropDown = OptionMenu(mainFrame, self.currentGame, self.gameList[0], *self.gameList) gameDropDown.pack(side=TOP) # create start game button startGameButton = Button(mainFrame, text="Start") startGameButton.bind("<Button-1>", self.startGame) startGameButton.pack(side=TOP) # create label and set text self.playerString = StringVar() self.playerString.set(self.buildPlayerHeaderString()) headerLabel = Label(topFrame, textvariable=self.playerString, style="GRN.TLabel") headerLabel.pack(side=TOP) addButton.bind("<Button-1>", self.onAddPlayerClick) self.playerNameEntry.bind("<Key>", self.onAddPlayerEnter) #set focus self.playerNameEntry.focus() def startGame(self,event): "starts the selected game" if self.playerList: mainFrame.pack_forget() gameFrame = Frame(root) gameFrame.pack(fill=BOTH, expand=1) game = self.currentGame.get() if game == "301": gameX01.GameX01(gameFrame, self.playerList) elif game == "501": gameX01.GameX01(gameFrame, self.playerList, 501) elif game == "Clock": gameClock.GameClock(gameFrame, self.playerList) else: gameX01.GameX01(gameFrame, self.playerList)
class PopupFrame(Toplevel): # ОПРЕДЕЛЯЕМ ГЛАВНОЕ ОКНО для РАБОТЫ С ДАННЫМИ; def __init__(self): super().__init__(root) self.init_frame() self.view = appl def init_frame(self): self.resizable(False, False) # СТИЛЬ ШРИФТА; font_style = ('Consolas', '12') # НИЖНЯЯ ПАНЕЛЬ ОШИБОК; self.TB_M_ = Frame(self, bg='#EDF0F5', bd=1, relief=FLAT) self.LBL_1 = Label(self.TB_M_) self.TBbtn = Frame(self.TB_M_) self.LBL_2 = Label(self.TB_M_) self.TB_M_.pack(fill=X) self.LBL_1.pack(side=BOTTOM) self.TBbtn.pack(side=BOTTOM) self.LBL_2.pack(side=BOTTOM) # МЕТКИ, ПОЛЕ и РАСКРЫВАЮЩИЕСЯ СПИСКИ; kino = [ [ 'Кино', 'Сериал', 'Мультфильм' ], [ 'Боевик', 'Драма', 'Комедия', 'Приключения', 'Триллер', 'Ужасы', 'Фантастика', 'Эротика' ], [ 'Просмотрено', 'Непросмотрено' ] ] self.L_name = Label(self.TB_M_, text='Название') self.L_mors = Label(self.TB_M_, text='Кино/Сериал/Мультфильм') self.L_janr = Label(self.TB_M_, text='Жанр') self.L_view = Label(self.TB_M_, text='Просмотр') self.count_chars = Label(self.TB_M_, font=('Consolas', '7')) self.len_mx = StringVar() # Максимальная длина символов в поле; self.name__ = Entry(self.TB_M_, width=41, font=font_style, textvariable=self.len_mx) self.len_mx.trace_variable('w', self.def_max_count_chars) self.mors__ = Combobox(self.TB_M_, values=kino[0], width=39, font=font_style, state='readonly') self.janr__ = Combobox(self.TB_M_, values=kino[1], width=39, font=font_style, state='readonly') self.view__ = Combobox(self.TB_M_, values=kino[2], width=39, font=font_style, state='readonly') self.L_name.pack(side=TOP) self.name__.pack(side=TOP) self.L_mors.pack(side=TOP) self.mors__.pack(side=TOP) self.L_janr.pack(side=TOP) self.janr__.pack(side=TOP) self.L_view.pack(side=TOP) self.view__.pack(side=TOP) self.name__.focus() self.mors__.current(0) self.janr__.current(0) self.view__.current(0) # КНОПКА для ЗАКРЫТИЯ ОКНА; self.btn_can = Button(self.TBbtn, text='Закрыть', width=25, command=self.destroy) self.btn_can.pack(side=RIGHT) # УДЕРЖИВАЕМ НАШЕ ДИАЛОГОВОЕ ОКНО 'НА ВЕРХУ'; self.grab_set() self.focus_set() def def_max_count_chars(self, name, index, mode): msg = self.len_mx.get() self.count_chars['text'] = '%d/%d' % (len(self.name__.get()), 40) if len(msg) > 40: self.len_mx.set(msg[:-1]) #self.len_mx.set(msg[0:39]) print(self.len_mx.set(msg[0:39]))
txt.configure(state = "normal") txt.insert(END, line) # Instead of returning it, why not just insert it here? txt.configure(state = "disabled") txt.see("end") f.close() idCount += len(lines) root.after(1000, loop) #l1select = l1.bind('<<ListboxSelect>>',lambda event: onselect(event, 'Test')) txt = scrolledtext.ScrolledText(root) txt.grid(row=0, column=0, rowspan=3, padx=10, pady=5, columnspan=3, sticky=E+W+S+N) txt.configure(state = "disabled") E1 = Entry(root) E1.grid(row = 4, columnspan = 3, sticky = E+W) E1.bind("<Return>", lambda event = None: push()) E1.focus() root.after(1000, loop) root.mainloop()
def entry_string(parent, lf_text, mess_text, out_var): """String layout for entry 06layout_string converted to a function Parameters ---------- parent : str parent handle lf_text : str text on LabelFrame mess_text : str message out_var : float tkvar handle Returns ------- string """ st1 = Style() st1.theme_use('default') st1.configure('brown.TLabelframe', background='#C9B99B') st1.configure('brown.TLabelframe.Label', background='#EDEF77') st1.configure('brown.TLabel', background='#EDEF77') lf0 = Labelframe(parent, text=lf_text, style='brown.TLabelframe') lf0.grid(column=0, row=0, padx=10, pady=10) def end_input(_evt): """limit on string Parameters ---------- evt : str bind handle Returns ------- None """ if len(entsv.get()) > 5: mee_lbl['text'] = "That's OK" out_var.set(entsv.get()) else: mee_lbl['text'] = "Should be at least 6 characters long" def is_okay(text, input, index): """ validation function Parameters ---------- text : str text if allowed input : str current inputut index : str indexex Returns ------- boolean """ index = int(index) print(index) if (input.isalnum() or input in (",", ".", "'", " ")) and index > 0: return True else: return bool((text.isupper() or text == "") and index == 0) vcmd = lf0.register(is_okay) entsv = StringVar() ent0 = Entry(lf0, validate='key', textvariable=entsv, validatecommand=(vcmd, '%P', '%S', '%i')) ent0.bind("<Return>", end_input) ent0.grid(row=1, column=0, padx=10) ent0.focus() mee_lbl = Label(lf0, text=mess_text, style='brown.TLabel') mee_lbl.grid(row=2, column=0, pady=10, padx=10)
class fiveOhOne: def __init__(self, master, player1name, player2name, numbersets, numberlegs): self.master = master self.frame = Frame(self.master) self.player1name = player1name self.player2name = player2name self.numbersets = numbersets self.numberlegs = numberlegs game_state.setup(self.player1name, self.player2name, self.numbersets, self.numberlegs) self.configure_gui1() self.who_starts(game_state.currentsets, game_state.currentlegs) #self.player_setup(player1name, player2name) self.counter = 0 self.stats_update(player1, player2) self.pl1avg.set(0) self.pl2avg.set(0) def configure_gui1(self): self.master.title("501") self.master.geometry("600x500") # function binding return key to entry box self.master.bind('<Return>', lambda e: self.score_Entered()) #create frames labFrame1 = LabelFrame(self.master, text="Player1 Stats") labFrame2 = LabelFrame(self.master, text="Player2 Stats") labFrame3 = LabelFrame(self.master, text="Player1 Scores") labFrame4 = LabelFrame(self.master, text="Player2 Scores") labFrame5 = LabelFrame(self.master, text="Enter Scores") #self.labFrame6 = LabelFrame(self.master, text="Additional info") #make frames vis(ible labFrame1.grid(row=0, column=0, rowspan=2, sticky='ns') labFrame3.grid(row=0, column=1) labFrame4.grid(row=0, column=2) labFrame2.grid(row=0, column=3, rowspan=2, sticky='ns') labFrame5.grid(row=1, column=1, columnspan=2, sticky='ew') #self.labFrame6.grid(row=3, column=1, columnspan=2, sticky='ew') #stringvars self.pl1name = StringVar() self.pl2name = StringVar() self.pl1sets = StringVar() self.pl1legs = StringVar() self.pl160 = StringVar() self.pl180 = StringVar() self.pl1100 = StringVar() self.pl1140 = StringVar() self.pl1180 = StringVar() self.pl1avg = StringVar() self.pl1chtpc = StringVar() self.pl1chtnumbs = StringVar() #player to go boolean self.player1_togo = True #frame 1 widgets Label(labFrame1, text="Totals").grid(row=0, column=0, sticky='w') Label(labFrame1, text="Sets:").grid(row=1, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1sets).grid(row=1, column=1) Label(labFrame1, text="Legs:").grid(row=2, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1legs).grid(row=2, column=1) Label(labFrame1, text="60+:").grid(row=3, column=0, sticky='w') Label(labFrame1, textvariable=self.pl160).grid(row=3, column=1) Label(labFrame1, text="80+:").grid(row=4, column=0, sticky='w') Label(labFrame1, textvariable=self.pl180).grid(row=4, column=1) Label(labFrame1, text="100+:").grid(row=5, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1100).grid(row=5, column=1) Label(labFrame1, text="140+:").grid(row=6, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1140).grid(row=6, column=1) Label(labFrame1, text="180:").grid(row=7, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1180).grid(row=7, column=1) Label(labFrame1, text="Averages").grid(row=8, column=0, sticky='w') Label(labFrame1, text="Score:").grid(row=9, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1avg).grid(row=9, column=1) Label(labFrame1, text="Checkout %:").grid(row=10, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1chtpc).grid(row=10, column=1) Label(labFrame1, text="Checkout Hit/Thrown:").grid(row=11, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1chtnumbs).grid(row=11, column=1) #stringvars self.pl2sets = StringVar() self.pl2legs = StringVar() self.pl260 = StringVar() self.pl280 = StringVar() self.pl2100 = StringVar() self.pl2140 = StringVar() self.pl2180 = StringVar() self.pl2avg = StringVar() self.pl2chtpc = StringVar() self.pl2chtnumbs = StringVar() #frame 2 widgets Label(labFrame2, text="Totals").grid(row=0, column=0, sticky='w') Label(labFrame2, text="Sets:").grid(row=1, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2sets).grid(row=1, column=1) Label(labFrame2, text="Legs:").grid(row=2, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2legs).grid(row=2, column=1) Label(labFrame2, text="60+:").grid(row=3, column=0, sticky='w') Label(labFrame2, textvariable=self.pl260).grid(row=3, column=1) Label(labFrame2, text="80+:").grid(row=4, column=0, sticky='w') Label(labFrame2, textvariable=self.pl280).grid(row=4, column=1) Label(labFrame2, text="100+:").grid(row=5, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2100).grid(row=5, column=1) Label(labFrame2, text="140+:").grid(row=6, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2140).grid(row=6, column=1) Label(labFrame2, text="180:").grid(row=7, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2180).grid(row=7, column=1) Label(labFrame2, text="Averages").grid(row=8, column=0, sticky='w') Label(labFrame2, text="Score:").grid(row=9, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2avg).grid(row=9, column=1) Label(labFrame2, text="Checkout %:").grid(row=10, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2chtpc).grid(row=10, column=1) Label(labFrame2, text="Checkout Hit/Thrown:").grid(row=11, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2chtnumbs).grid(row=11, column=1) #frame 3 widgets self.pl1remaining = StringVar() Label(labFrame3, text="Player:").grid(row=0, column=0) Label(labFrame3, textvariable=self.pl1name).grid(row=0, column=1) Label(labFrame3).grid(row=1) Label(labFrame3, text="Remaining").grid(row=2, column=0, columnspan=2, sticky='ew') self.remlabel1 = Label(labFrame3, textvariable=self.pl1remaining) self.remlabel1.grid(row=3, column=0, columnspan=2) self.remlabel1.configure(width=3, background='white', font=(None, 35)) #self.pl1remaining.set(self.pl1dict['score']) self.pl1name.set(game_state.player1) #frame 4 widgets self.pl2remaining = StringVar() Label(labFrame4, text="Player:").grid(row=0, column=0) Label(labFrame4, textvariable=self.pl2name).grid(row=0, column=1) Label(labFrame4).grid(row=1) Label(labFrame4, text="Remaining").grid(row=2, column=0, columnspan=2, sticky='ew') self.remlabel2 = Label(labFrame4, textvariable=self.pl2remaining) self.remlabel2.grid(row=3, column=0, columnspan=2) self.remlabel2.configure(width=3, background='white', font=(None, 35)) #self.pl2remaining.set(self.pl2dict['score']) self.pl2name.set(game_state.player2) #frame 5 widgets self.playertogo = StringVar() self.scoreEntered = StringVar() Label(labFrame5, text=" ").grid(row=0, column=0) #Label(labFrame5).grid(row=0, column=1) #Label(labFrame5).grid(row=0, column=2) Label(labFrame5, text="To Go:").grid(row=1, column=1) playerLabel = Label(labFrame5, textvariable=self.playertogo) playerLabel.grid(row=2, column=1) playerLabel.configure(font=(None, 20)) self.number_entry = Entry(labFrame5, textvariable=self.scoreEntered, width=5) self.number_entry.grid(row=2, column=2) self.number_entry.configure(background='white', font=(None, 20)) self.number_entry.focus() def stats_update(self, player1, player2): self.pl1sets.set(player1.stats['sets']) self.pl1legs.set(player1.stats['legs']) self.pl1remaining.set(player1.stats['score']) self.pl160.set(player1.stats['60+']) self.pl180.set(player1.stats['80+']) self.pl1100.set(player1.stats['100+']) self.pl1140.set(player1.stats['140+']) self.pl1180.set(player1.stats['180']) numbset = ( "%s / %s" % (player1.stats['doubleshit'], player1.stats['dartsatdoubles'])) self.pl1chtnumbs.set(numbset) #if player1.stats['dartsatdoubles'] == 0: #player1.stats['doubleshit'] = 1 #pc1 = (player1.stats['dartsatdoubles']/player1.stats['doubleshit']) self.pl1chtpc.set(player1.stats['checkoutpc']) average1 = (player1.stats['totalScore'] / player1.stats['numberDarts']) * 3 average1 = round(average1, 2) self.pl1avg.set(average1) #self.remlabel1.configure(background='yellow') #self.playertogo.set(self.player1name) self.pl2sets.set(player2.stats['sets']) self.pl2legs.set(player2.stats['legs']) self.pl2remaining.set(player2.stats['score']) self.pl260.set(player2.stats['60+']) self.pl280.set(player2.stats['80+']) self.pl2100.set(player2.stats['100+']) self.pl2140.set(player2.stats['140+']) self.pl2180.set(player2.stats['180']) self.pl2avg.set(player2.stats['avg']) numbset2 = ( "%s / %s" % (player2.stats['doubleshit'], player2.stats['dartsatdoubles'])) self.pl2chtnumbs.set(numbset2) #if player2.stats['dartsatdoubles'] == 0: #player2.stats['doubleshit'] = 1 #pc2 = (player2.stats['dartsatdoubles']/player2.stats['doubleshit']) self.pl2chtpc.set(player2.stats['checkoutpc']) average2 = (player2.stats['totalScore'] / player2.stats['numberDarts']) * 3 average2 = round(average2, 2) self.pl2avg.set(average2) self.counter += 1 def who_starts(self, sets, legs): if sets % 2 != 0: if legs % 2 != 0: self.playertogo.set(self.player1name) self.remlabel1.configure(background='yellow') self.remlabel2.configure(background='white') player1.stats['score'] = 501 player2.stats['score'] = 501 game_state.playertogo = 1 else: self.playertogo.set(self.player2name) self.remlabel2.configure(background='yellow') self.remlabel1.configure(background='white') player1.stats['score'] = 501 player2.stats['score'] = 501 game_state.playertogo = 2 else: if legs % 2 != 0: self.playertogo.set(self.player2name) self.remlabel2.configure(background='yellow') self.remlabel1.configure(background='white') player1.stats['score'] = 501 player2.stats['score'] = 501 game_state.playertogo = 2 else: self.playertogo.set(self.player1name) self.remlabel1.configure(background='yellow') self.remlabel2.configure(background='white') player1.stats['score'] = 501 player2.stats['score'] = 501 game_state.playertogo = 1 def score_Entered(self): self.dartsatdouble = StringVar() if self.counter == 1: player1.stats['totalScore'] = 0 player1.stats['numberDarts'] = 0 elif self.counter == 2: player2.stats['totalScore'] = 0 player2.stats['numberDarts'] = 0 self.score = int(self.scoreEntered.get()) if game_state.playertogo == 1: player1.stats['score'] -= self.score player1.stats['totalScore'] += self.score player1.stats['numberDarts'] += 3 player1.status(self.score, player1) self.stats_update(player1, player2) self.playertogo.set(self.player2name) self.remlabel2.configure(background='yellow') self.remlabel1.configure(background='white') if (player1.stats['score'] >= 0) and (player1.stats['score'] < 50): self.dartsAtDouble = Toplevel() Label(self.dartsAtDouble, text="Darts at Double: ").grid(row=1, column=0) self.doubleDarts = Combobox(self.dartsAtDouble, width=5, textvariable=self.dartsatdouble) self.doubleDarts.bind("<<ComboboxSelected>>", self.darts_at_double) self.doubleDarts['values'] = ('0', '1', '2', '3') self.doubleDarts.grid(row=1, column=1) #root.wait_window(darts_at_double) #self.doubleDarts.grid() #self.doubleDarts_label.grid() self.number_entry.delete(0, END) game_state.playertogo = 2 else: player2.stats['score'] -= self.score player2.stats['totalScore'] += self.score player2.stats['numberDarts'] += 3 player2.status(self.score, player2) self.stats_update(player1, player2) self.playertogo.set(self.player1name) self.remlabel1.configure(background='yellow') self.remlabel2.configure(background='white') if (player2.stats['score'] >= 0) and (player2.stats['score'] < 50): self.dartsAtDouble = Toplevel() Label(self.dartsAtDouble, text="Darts at Double: ").grid(row=1, column=0) self.doubleDarts = Combobox(self.dartsAtDouble, width=5, textvariable=self.dartsatdouble) self.doubleDarts.bind("<<ComboboxSelected>>", self.darts_at_double) self.doubleDarts['values'] = ('0', '1', '2', '3') self.doubleDarts.grid(row=1, column=1) self.number_entry.delete(0, END) game_state.playertogo = 1 def darts_at_double(self, player): self.legwondarts = StringVar() self.darts_at_doubles = int(self.dartsatdouble.get()) if player1.stats['score'] == 0: self.legWon = Toplevel() Label(self.legWon, text="Darts Used: ").grid(row=1, column=0) self.leg_won = Combobox(self.legWon, width=5, textvariable=self.legwondarts) self.leg_won.bind("<<ComboboxSelected>>", self.leg_won_darts) self.leg_won['values'] = ('1', '2', '3') self.leg_won.grid(row=1, column=1) elif player2.stats['score'] == 0: self.legWon = Toplevel() Label(self.legWon, text="Darts Used: ").grid(row=1, column=0) self.leg_won = Combobox(self.legWon, width=5, textvariable=self.legwondarts) self.leg_won.bind("<<ComboboxSelected>>", self.leg_won_darts) self.leg_won['values'] = ('1', '2', '3') self.leg_won.grid(row=1, column=1) if game_state.playertogo == 2: player1.stats['dartsatdoubles'] += self.darts_at_doubles else: player2.stats['dartsatdoubles'] += self.darts_at_doubles self.stats_update(player1, player2) self.dartsAtDouble.destroy() def leg_won_darts(self, last_Darts): lastDarts = int(self.legwondarts.get()) if game_state.playertogo == 2: player1.stats['numberDarts'] -= (3 - lastDarts) player1.stats['legs'] += 1 player1.stats['doubleshit'] += 1 player1.stats['checkoutpc'] = round( player1.stats['doubleshit'] / player1.stats['dartsatdoubles'] * 100, 2) game_state.currentlegs += 1 if player1.stats['legs'] == game_state.legs: player1.stats['sets'] += 1 player1.stats['legs'] = 0 player2.stats['legs'] = 0 game_state.currentsets += 1 game_state.currentlegs = 1 self.who_starts(game_state.currentsets, game_state.currentlegs) else: player2.stats['numberDarts'] -= (3 - lastDarts) player2.stats['legs'] += 1 player2.stats['doubleshit'] += 1 player2.stats['checkoutpc'] = round( player2.stats['doubleshit'] / player2.stats['dartsatdoubles'] * 100, 2) game_state.currentlegs += 1 if player2.stats['legs'] == game_state.legs: player2.stats['sets'] += 1 player2.stats['legs'] = 0 player2.stats['legs'] = 0 game_state.currentsets += 1 game_state.currentlegs = 1 self.who_starts(game_state.currentsets, game_state.currentlegs) self.who_starts(game_state.currentsets, game_state.currentlegs) self.stats_update(player1, player2) self.legWon.destroy() print(player1.stats['sets']) print(player2.stats['sets']) print(game_state.sets) if player1.stats['sets'] == game_state.sets: self.game_won() elif player1.stats['sets'] == game_state.sets: self.game_won() def game_won(self): self.gamewonwindow = Toplevel() Label(self.gamewonwindow, text="Totals").grid(row=0, column=0, sticky='w') Label(self.gamewonwindow, text="Sets:").grid(row=1, column=0, sticky='w') Label(self.gamewonwindow, textvariable=self.pl1sets).grid(row=1, column=1) Label(self.gamewonwindow, textvariable=self.pl2sets).grid(row=1, column=2) Label(self.gamewonwindow, text="Legs:").grid(row=2, column=0, sticky='w') Label(self.gamewonwindow, textvariable=self.pl1legs).grid(row=2, column=1) Label(self.gamewonwindow, textvariable=self.pl2legs).grid(row=2, column=2) Label(self.gamewonwindow, text="60+:").grid(row=3, column=0, sticky='w') Label(self.gamewonwindow, textvariable=self.pl160).grid(row=3, column=1) Label(self.gamewonwindow, textvariable=self.pl260).grid(row=3, column=2) Label(self.gamewonwindow, text="80+:").grid(row=4, column=0, sticky='w') Label(self.gamewonwindow, textvariable=self.pl180).grid(row=4, column=1) Label(self.gamewonwindow, textvariable=self.pl280).grid(row=4, column=2) Label(self.gamewonwindow, text="100+:").grid(row=5, column=0, sticky='w') Label(self.gamewonwindow, textvariable=self.pl1100).grid(row=5, column=1) Label(self.gamewonwindow, textvariable=self.pl2100).grid(row=5, column=2) Label(self.gamewonwindow, text="140+:").grid(row=6, column=0, sticky='w') Label(self.gamewonwindow, textvariable=self.pl1140).grid(row=6, column=1) Label(self.gamewonwindow, textvariable=self.pl2140).grid(row=6, column=2) Label(self.gamewonwindow, text="180:").grid(row=7, column=0, sticky='w') Label(self.gamewonwindow, textvariable=self.pl1180).grid(row=7, column=1) Label(self.gamewonwindow, textvariable=self.pl2180).grid(row=7, column=2) Label(self.gamewonwindow, text="Averages").grid(row=8, column=0, sticky='w') Label(self.gamewonwindow, text="Score:").grid(row=9, column=0, sticky='w') Label(self.gamewonwindow, textvariable=self.pl1avg).grid(row=9, column=1) Label(self.gamewonwindow, textvariable=self.pl2avg).grid(row=9, column=2) Label(self.gamewonwindow, text="Checkout %:").grid(row=10, column=0, sticky='w') Label(self.gamewonwindow, textvariable=self.pl1chtpc).grid(row=10, column=1) Label(self.gamewonwindow, textvariable=self.pl2chtpc).grid(row=10, column=2) Label(self.gamewonwindow, text="Checkout Hit/Thrown:").grid(row=11, column=0, sticky='w') Label(self.gamewonwindow, textvariable=self.pl1chtnumbs).grid(row=11, column=1) Label(self.gamewonwindow, textvariable=self.pl2chtnumbs).grid(row=11, column=2)
""" print(text) index = int(index) if text.isupper() and index == 0: return True if input in (",", ".", "'", " ") and index > 0: return True if inp.isalnum() and index > 0: return True if text == "": return True else: return False vcmd = root.register(is_okay) entsv = StringVar() ent0 = Entry(lf0, validate='key', validatecommand=(vcmd, '%P', '%S', '%i'), textvariable=entsv) ent0.bind("<Return>", end_input) ent0.grid(row=1, column=0, padx=10) ent0.focus() mess_lbl = Label(lf0, text='Start with capital letter, <Return> to confirm') mess_lbl.grid(row=2, column=0, pady=10, padx=10) root.mainloop()
class fiveOhOne: def __init__(self, master): self.master = master self.frame = Frame(self.master) self.configure_gui1() def configure_gui1(self): self.master.title("501") self.master.geometry("800x600") # function binding return key to entry box self.master.bind('<Return>', lambda e: self.score_Entered()) #create menu def callback(): print("called the callback!") # create a menu menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New", command=callback) filemenu.add_command(label="Open...", command=callback) filemenu.add_separator() filemenu.add_command(label="Exit", command=callback) helpmenu = Menu(menu) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=callback) #create frames labFrame1 = LabelFrame(self.master, text="Player1 Stats") labFrame2 = LabelFrame(self.master, text="Player2 Stats") labFrame3 = LabelFrame(self.master, text="Player1 Scores") labFrame4 = LabelFrame(self.master, text="Player2 Scores") labFrame5 = LabelFrame(self.master, text="Enter Scores") """ #make frames visible using grid labFrame1.grid(row=0, column=0, rowspan=2, sticky='ew') labFrame3.grid(row=0, column=1, sticky='ew') labFrame4.grid(row=0, column=2, sticky='ew') labFrame2.grid(row=0, column=3, rowspan=2, sticky='ew') labFrame5.grid(row=1, column=1, columnspan=2, sticky='ew') """ #make frames visible using pack labFrame1.pack(side="left", fill="both", expand=True) labFrame2.pack(side="right", fill="both", expand=True) labFrame5.pack(side="bottom", fill="x", expand=True) labFrame3.pack(side="left", fill="both", expand=True) labFrame4.pack(side="right", fill="both", expand=True) #stringvars self.pl1name = StringVar() self.pl2name = StringVar() self.pl1sets = StringVar() self.pl1legs = StringVar() self.pl160 = StringVar() self.pl180 = StringVar() self.pl1100 = StringVar() self.pl1140 = StringVar() self.pl1180 = StringVar() self.pl1avg = StringVar() self.pl1chtpc = StringVar() self.pl1chtnumbs = StringVar() #player to go boolean self.player1_togo = True #frame 1 widgets Label(labFrame1, text="Totals").grid(row=0, column=0, sticky='w') Label(labFrame1, text="Sets:").grid(row=1, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1sets).grid(row=1, column=1) Label(labFrame1, text="Legs:").grid(row=2, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1legs).grid(row=2, column=1) Label(labFrame1, text="60+:").grid(row=3, column=0, sticky='w') Label(labFrame1, textvariable=self.pl160).grid(row=3, column=1) Label(labFrame1, text="80+:").grid(row=4, column=0, sticky='w') Label(labFrame1, textvariable=self.pl180).grid(row=4, column=1) Label(labFrame1, text="100+:").grid(row=5, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1100).grid(row=5, column=1) Label(labFrame1, text="140+:").grid(row=6, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1140).grid(row=6, column=1) Label(labFrame1, text="180:").grid(row=7, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1180).grid(row=7, column=1) Label(labFrame1, text="Averages").grid(row=8, column=0, sticky='w') Label(labFrame1, text="Score:").grid(row=9, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1avg).grid(row=9, column=1) Label(labFrame1, text="Checkout %:").grid(row=10, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1chtpc).grid(row=10, column=1) Label(labFrame1, text="Checkout Hit/Thrown:").grid(row=11, column=0, sticky='w') Label(labFrame1, textvariable=self.pl1chtnumbs).grid(row=11, column=1) #stringvars self.pl2sets = StringVar() self.pl2legs = StringVar() self.pl260 = StringVar() self.pl280 = StringVar() self.pl2100 = StringVar() self.pl2140 = StringVar() self.pl2180 = StringVar() self.pl2avg = StringVar() self.pl2chtpc = StringVar() self.pl2chtnumbs = StringVar() #frame 2 widgets Label(labFrame2, text="Totals").grid(row=0, column=0, sticky='w') Label(labFrame2, text="Sets:").grid(row=1, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2sets).grid(row=1, column=1) Label(labFrame2, text="Legs:").grid(row=2, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2legs).grid(row=2, column=1) Label(labFrame2, text="60+:").grid(row=3, column=0, sticky='w') Label(labFrame2, textvariable=self.pl260).grid(row=3, column=1) Label(labFrame2, text="80+:").grid(row=4, column=0, sticky='w') Label(labFrame2, textvariable=self.pl280).grid(row=4, column=1) Label(labFrame2, text="100+:").grid(row=5, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2100).grid(row=5, column=1) Label(labFrame2, text="140+:").grid(row=6, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2140).grid(row=6, column=1) Label(labFrame2, text="180:").grid(row=7, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2180).grid(row=7, column=1) Label(labFrame2, text="Averages").grid(row=8, column=0, sticky='w') Label(labFrame2, text="Score:").grid(row=9, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2avg).grid(row=9, column=1) Label(labFrame2, text="Checkout %:").grid(row=10, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2chtpc).grid(row=10, column=1) Label(labFrame2, text="Checkout Hit/Thrown:").grid(row=11, column=0, sticky='w') Label(labFrame2, textvariable=self.pl2chtnumbs).grid(row=11, column=1) #frame 3 widgets self.pl1remaining = StringVar() Label(labFrame3, text="Player:").grid(row=0, column=0) Label(labFrame3, textvariable=self.pl1name).grid(row=0, column=1) Label(labFrame3).grid(row=1) Label(labFrame3, text="Remaining").grid(row=2, column=0, columnspan=2, sticky='ew') self.remlabel1 = Label(labFrame3, textvariable=self.pl1remaining) self.remlabel1.grid(row=3, column=0, columnspan=2) self.remlabel1.configure(width=3, background='white', font=(None, 35)) #self.pl1remaining.set(self.pl1dict['score']) #self.pl1name.set(game_state.player1) #frame 4 widgets self.pl2remaining = StringVar() Label(labFrame4, text="Player:").grid(row=0, column=0) Label(labFrame4, textvariable=self.pl2name).grid(row=0, column=1) Label(labFrame4).grid(row=1) Label(labFrame4, text="Remaining").grid(row=2, column=0, columnspan=2, sticky='ew') self.remlabel2 = Label(labFrame4, textvariable=self.pl2remaining) self.remlabel2.grid(row=3, column=0, columnspan=2) self.remlabel2.configure(width=3, background='white', font=(None, 35)) #self.pl2remaining.set(self.pl2dict['score']) #self.pl2name.set(game_state.player2) #frame 5 widgets self.playertogo = StringVar() self.scoreEntered = StringVar() Label(labFrame5, text=" ").grid(row=0, column=0) #Label(labFrame5).grid(row=0, column=1) #Label(labFrame5).grid(row=0, column=2) Label(labFrame5, text="To Go:").grid(row=1, column=1) playerLabel = Label(labFrame5, textvariable=self.playertogo) playerLabel.grid(row=2, column=1) playerLabel.configure(font=(None, 20)) self.number_entry = Entry(labFrame5, textvariable=self.scoreEntered, width=5) self.number_entry.grid(row=2, column=2) self.number_entry.configure(background='white', font=(None, 20)) self.number_entry.focus()
class SignInView(Frame): def __init__(self, master): super().__init__(master=master) self.layout_components() # Setup Callbacks self.show_register: Callable = None self.sign_in: Callable = None self.user_Entry.focus() def layout_components(self): self.pack(fill=tk.BOTH, expand=False, padx=PADX, pady=PADY) error_font = font.Font(family="Ariel", size=8) # Variables self.username = tk.StringVar() self.username.set("") self.password = tk.StringVar() self.password.set("") # Username Row user_Frame = Frame(self) user_Frame.pack(fill=tk.X) user_Label = Label(user_Frame, text="Username:"******"<FocusOut>", self.enable_sign_in) self.user_Entry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True) # Password Row pass_Frame = Frame(self) pass_Frame.pack(fill=tk.X) pass_Label = Label(pass_Frame, text="Password:"******"*") self.pass_Entry.bind("<FocusOut>", self.enable_sign_in) self.pass_Entry.pack(fill=tk.X, padx=PADX, pady=PADY, expand=True) # Error Row err_Frame = Frame(self) err_Frame.pack(fill=tk.X) self.err_Label = Label(err_Frame, text="", foreground="red", font=error_font) self.err_Label.pack(side=tk.LEFT, anchor="center", expand=True, padx=PADX, pady=PADY) # Button Row button_Frame = Frame(self) button_Frame.pack(fill=tk.X) # Cancel Button cncl_Button = Button(button_Frame, text="Cancel", command=self.cancel) cncl_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False) # Sign in Button self.sgnn_Button = Button(button_Frame, text="Sign in", state="disabled", command=self._sign_in) self.sgnn_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False) # Register Row register_Frame = Frame(self) register_Frame.pack(fill=tk.X) register_Button = Button(register_Frame, text="Register", command=self._show_register) register_Button.pack(side=tk.RIGHT, padx=PADX, pady=PADY, expand=False) register_Label = Label(register_Frame, text="Not a Member of ExchangeGram?") register_Label.pack(side=tk.RIGHT, padx=PADX, pady=PADY) def _sign_in(self): if self.sign_in is not None: self.sign_in() def enable_sign_in(self, event): if self.username.get() != "" and self.password.get() != "": self.sgnn_Button.configure(state="normal") else: self.sgnn_Button.configure(state="disabled") def failed_sign_in(self): self.err_Label.configure(text="Username/Password Incorrect") def cancel(self): self.username.set("") self.password.set("") self.user_Entry.focus() def _show_register(self): if self.show_register is not None: self.cancel() self.show_register() else: pass
class Search(Module): def __init__(self, app): self.app = app self.window = None self.context_size = 3 self.results = [] self.regex = StringVar(self.app) # if anything ever changes the contents of any intervals # it should call SearchModule.loadIntervals() self.intervals = [] self.loadIntervals() def handleClose(self, event=None): self.window.destroy() self.window = None def createWindow(self): self.window = Toplevel(self.app) self.window.title('Search') self.window.protocol("WM_DELETE_WINDOW", self.handleClose) self.input = Entry(self.window, textvariable=self.regex) self.input.grid(row=0, column=0) self.input.bind('<Return>', self.search) self.input.bind('<Escape>', lambda ev: self.window.focus()) self.searchButton = Button(self.window, text='Search', command=self.search, takefocus=0) self.searchButton.grid(row=0, column=1) self.resultCount = Label(self.window, text='0 results') self.resultCount.grid(row=0, column=2) cols = ('File', 'Tier', 'Time', 'Text') self.scroll = Scrollbar(self.window, orient='vertical') self.resultList = Treeview(self.window, columns=cols, show="headings", yscrollcommand=self.scroll.set, selectmode='browse') self.scroll.config(command=self.resultList.yview) for col in cols: self.resultList.heading(col, text=col) self.resultList.grid(row=2, column=0, columnspan=3, sticky='news') self.resultList.bind('<Double-1>', self.onClick) Grid.rowconfigure(self.window, 2, weight=1) Grid.columnconfigure(self.window, 0, weight=1) self.scroll.grid(row=2, column=3, sticky='ns') def openSearch(self): if self.window == None: self.createWindow() self.window.lift() self.input.focus() def loadIntervals(self): filecount = len(self.app.Data.getTopLevel('files')) self.intervals = [] for f in range(filecount): filename = self.app.Data.getFileLevel('name', f) tg = self.app.Data.checkFileLevel('.TextGrid', f, shoulderror=False) if tg: grid = self.app.TextGrid.fromFile(tg) for tier in grid: if TextGrid.isIntervalTier(tier): for el in tier: if el.mark: self.intervals.append( (el, tier.name, filename)) def search(self, event=None): if self.regex.get() == '': self.results = [] else: pat = re.compile(self.regex.get(), re.IGNORECASE | re.MULTILINE | re.DOTALL) self.results = [] for i in self.intervals: s = pat.search(i[0].mark) if s: disp = i[0].mark a = max(0, s.start() - self.context_size) b = min(s.end() + self.context_size, len(disp)) self.results.append(i + (('...' if a > 0 else '') + disp[a:b] + ('...' if b < len(disp) else ''), )) self.resultCount.configure(text='%s results' % len(self.results)) for kid in self.resultList.get_children(): self.resultList.delete(kid) for row, res in enumerate(self.results): ls = (res[2], res[1], '%s-%s' % (res[0].minTime, res[0].maxTime), res[3]) self.resultList.insert('', 'end', iid=str(row), values=ls) def onClick(self, event=None): self.jumpTo(int(self.resultList.selection()[0])) def jumpTo(self, index): self.app.filesJumpTo(self.results[index][2]) self.app.TextGrid.selectedTier.set(self.results[index][1]) self.app.TextGrid.start = self.results[index][0].minTime self.app.TextGrid.end = self.results[index][0].maxTime for i, f in enumerate(self.app.TextGrid.frameTier): if f.time >= self.results[index][0].minTime: self.app.frameSV.set(str(i)) self.app.framesJumpTo() break self.app.TextGrid.fillCanvases() def reset(self, *args, **kwargs): raise NotImplementedError('cannot call SearchModule::reset') def update(self, *args, **kwargs): raise NotImplementedError('cannot call SearchModule::update') def grid(self, *args, **kwargs): raise NotImplementedError('cannot call SearchModule::grid') def grid_remove(self, *args, **kwargs): raise NotImplementedError('cannot call SearchModule::grid_remove')
def listchans(self, index=None, tagsearch="", archived=0, ob=Channel.displayname, so=asc): self.center = Frame(root, bg=config.bgcolor, width=50, height=40, padx=3, pady=3) # layout all of the main containers root.grid_rowconfigure(1, weight=1) root.grid_columnconfigure(0, weight=1) self.center.grid(row=1, sticky="nsew") channels = database.get_channels(archived, ob, so) if so == desc: so = asc else: so = desc tree = Treeview(self.center) sstring = Entry(self.center, width=config.textBoxWidth) sstring.bind( "<KeyRelease-Return>", lambda e: self.listchans(None, sstring.get(), archived, ob, so)) sstring.grid(column=0, row=0) if len(tagsearch) >= 1: sstring.focus() sstring.insert(0, tagsearch) searchbutton = Button(self.center, text="Search", command=lambda: self.listchans( None, sstring.get(), archived, ob, so)) searchbutton.grid(column=1, row=0) clearbutton = Button(self.center, text="Clear Search") clearbutton.configure(command=lambda: self.listchans(archived)) clearbutton.grid(column=3, row=0) tree["columns"] = ("one", "two") tree.column("#0", width=210, minwidth=10, stretch=YES) tree.column("one", width=350, minwidth=250, stretch=YES) tree.column("two", width=210, minwidth=10, stretch=YES) tree.heading("#0", text="Last Check", anchor=W, command=lambda: self.listchans(None, sstring.get( ), archived, Channel.lastcheck, so)) tree.heading("one", text="Channel Name", anchor=E, command=lambda: self.listchans(None, sstring.get( ), archived, Channel.displayname, so)) tree.heading("two", text="Last Published", command=lambda: self.listchans(None, sstring.get( ), archived, Channel.lastpub, so)) i = 0 tree.tag_configure('oddrow', background='#88DD88') tree.tag_configure('evenrow', background='#FFFFFF') tree.tag_configure('archivedodd', background="#88DD88", foreground="#aaaaaa") tree.tag_configure('archivedeven', background='#FFFFFF', foreground="#cccccc") for item in channels: foldername = "folder" + str(i) if i % 2 == 0: color = "evenrow" else: color = "oddrow" if item.archive == True: if i % 2 == 0: color = "archivedeven" else: color = "archivedodd" if tagsearch.lower() in str( item.displayname).lower() or tagsearch.lower() in str( item.dldir).lower() or tagsearch.lower() in str( item.yt_channelid).lower(): if item.lastpub == None: lastpub = "N/A" else: lastpub = time.ctime(item.lastpub) foldername = tree.insert("", "end", text=time.ctime(item.lastcheck), values=(item.displayname, lastpub), tags=(color, item.displayname, item.dldir, item.yt_channelid)) tree.insert(foldername, "end", text="Directory", values=(item.dldir, ), tags=(color)) tree.insert(foldername, "end", text="Last Published", values=(lastpub, ), tags=(color)) i = i + 1 vertscroll = Scrollbar(self.center) vertscroll.config(command=tree.yview) tree.config(yscrollcommand=vertscroll.set, height=20) vertscroll.grid(column=4, row=1, sticky='NSE') tree.bind("<Double-1>", self.item_selected) tree.grid(row=1, columnspan=4, sticky="NSEW") tree.focus(index) tree.selection_set(index) tree.see(index)
def _gui(): try: from tkinter import Tk, ttk, filedialog, messagebox, StringVar, IntVar from tkinter.ttk import Button, Entry, Frame, Label, LabelFrame, Notebook, Radiobutton, Style except: sys.exit("Unable to load tkinter. Aborting.") def _check_single(): #check the input and accordingly give the output... for the f_single tab if txt_f_single_entry.get()=="": lbl_f_single_result.config(text="", style="TLabel") elif check_afm(txt_f_single_entry.get()): lbl_f_single_result.config(text="Έγκυρο ΑΦΜ.", style="valid.TLabel") else: lbl_f_single_result.config(text="Άκυρο ΑΦΜ.", style="invalid.TLabel") def _select_input_file(): strv_f_file_input.set(filedialog.askopenfilename(title="Άνοιγμα αρχείου")) if strv_f_file_input.get() != "" and strv_f_file_output.get() != "": btn_f_file_submit.config(state="normal") else: btn_f_file_submit.config(state="disabled") #TODO a much better mechanism to enable / disable btn_f_file_submit is needed. def _select_output_file(): strv_f_file_output.set(filedialog.asksaveasfilename(title="Αποθήκευση ως...")) if strv_f_file_input.get() != "" and strv_f_file_output.get() != "": btn_f_file_submit.config(state="normal") else: btn_f_file_submit.config(state="disabled") def _check_file():#TODO this could / should be merged with the TUI version... input_filepath = strv_f_file_input.get() output_filepath = strv_f_file_output.get() filter_output = intvar_filter_sel.get() try: input_file = open(input_filepath, "r") output_file = open(output_filepath, "w") except: messagebox.showerror(title="Σφάλμα", message="Αδυναμία διαχείρησης των αρχείων που ορίσατε.\n\nΠαρακαλώ επιβεβαιώστε πως το αρχείο με τα δεδομένα υπάρχει, πως έχετε δικαιώματα ανάγνωσης, και πως έχετε δικαιώματα εγγραφής στον κατάλογο εξαγωγής των αποτελεσμάτων.") return counter = {True:0, False:0} for entry in input_file: validation = check_afm(entry.strip()) counter[validation]+=1 if filter_output == 3 and validation == False: output_file.write(entry) elif filter_output == 2 and validation == True: output_file.write(entry) elif filter_output == 1: output_file.write(entry.strip() + "\t" + str(validation) + "\n\r") lbl_f_file_result.config(text="Σύνολο: "+str(counter[True]+counter[False])+"\nΈγκυρα: "+str(counter[True])+"\nΆκυρα: "+str(counter[False])) #create the window main_window = Tk() main_window.title("Έλεγχος εγκυρότητας Α.Φ.Μ. (v 2.0)") main_window.geometry("600x180") main_window.minsize(600,180) #fool arround with styling style = ttk.Style() style.configure("valid.TLabel", background="green") style.configure("empty.TLabel", background="white") style.configure("invalid.TLabel", background="red") style.configure("TNotebook", padding = 10) #create the Notebook tabs = Notebook(main_window) f_single = Frame(tabs) f_file = Frame(tabs) tabs.add(f_single, text="Μεμονομένα Α.Φ.Μ.") tabs.add(f_file, text="Λίστα από αρχείο")#add state="disabled" prior to git push until ready tabs.pack(anchor="nw") #add some widgets in f_single tab lbl_f_single_instructions = Label(f_single, text="Εισάγετε έναν ΑΦΜ για έλεγχο") lbl_f_single_instructions.grid(column=0, row=0) lbl_f_single_result = Label(f_single, text="", width=10, justify="center") lbl_f_single_result.grid(column=1, row=0, rowspan=2, sticky="ewns") txt_f_single_entry = Entry(f_single, width=11) txt_f_single_entry.focus() txt_f_single_entry.bind("<KeyRelease>", lambda e: _check_single() ) txt_f_single_entry.grid(column=0,row=1) #btn_f_single_submit = Button(f_single, text="Έλεγχος", command=_check_single) #btn_f_single_submit.grid(column=0,row=2) #add some widgets in f_file tab lbl_f_file_finput = Label(f_file, text="Άνοιγμα...") lbl_f_file_finput.grid(column=0, row=0) strv_f_file_input = StringVar() txt_f_file_finput = Entry(f_file, textvariable = strv_f_file_input) txt_f_file_finput.grid(column=1, row=0) btn_f_file_finput = Button(f_file, text="...", width=3, command=_select_input_file) btn_f_file_finput.grid(column=2, row=0, sticky="W") lbl_f_file_foutput = Label(f_file, text="Αποθήκευση ως...") lbl_f_file_foutput.grid(column=0, row=1) strv_f_file_output = StringVar() txt_f_file_foutput = Entry(f_file, textvariable = strv_f_file_output) txt_f_file_foutput.grid(column=1, row=1) btn_f_file_foutput = Button(f_file, text="...", width=3, command=_select_output_file) btn_f_file_foutput.grid(column=2, row=1, sticky="W") lf_filter = LabelFrame(f_file, text="Επιστροφή") lf_filter.grid(column=3, row=0, rowspan=2, sticky="ewns") intvar_filter_sel = IntVar() rb_filter_all = Radiobutton(lf_filter, text="Όλων", variable=intvar_filter_sel, value=1) #TODO maybe add command rb_filter_all.pack(anchor="w") rb_filter_all.invoke() rb_filter_true = Radiobutton(lf_filter, text="Έγκυρων", variable=intvar_filter_sel, value=2) rb_filter_true.pack(anchor="w") rb_filter_false = Radiobutton(lf_filter, text="Άκυρων", variable=intvar_filter_sel, value=3) rb_filter_false.pack(anchor="w") lf_result = LabelFrame(f_file, text="Σύνοψη") lf_result.grid(column=4, row=0, rowspan=2, sticky="ewns") lbl_f_file_result = Label(lf_result, text="", width=12)#TODO bring results lbl_f_file_result.pack() btn_f_file_submit = Button(f_file, text="Επεξεργασία", state="disabled", command=_check_file) btn_f_file_submit.grid(column=0, row=2, columnspan=3) btn_main_exit = Button(main_window, text="Έξοδος", command=sys.exit) btn_main_exit.pack(anchor="se") main_window.mainloop()
class ManualMatchInputFrame(LabelFrame): title_input: Entry ratio_1_input: Entry ratio_x_input: Entry ratio_2_input: Entry def __init__(self, parent, matches: Matches, column=1, row=1): super().__init__(parent, text=" Manual input ") self._matches = matches self._var_title = StringVar() self._var_ratio_1 = DoubleVar() self._var_ratio_x = DoubleVar() self._var_ratio_2 = DoubleVar() self.grid(column=column, row=row, sticky=NSEW, padx=PAD_X, pady=PAD_Y) self.create_widgets() def create_widgets(self): Label(self, text="Title:").grid(column=0, row=0) Label(self, text="1:").grid(column=0, row=1) Label(self, text="X:").grid(column=0, row=2) Label(self, text="2:").grid(column=0, row=3) self.title_input = Entry(self, width=W_MATCH_TITLE, textvariable=self._var_title) self.title_input.grid(column=1, row=0, columnspan=2) self.title_input.focus() self.ratio_1_input = Entry(self, width=W_MATCH_RATIO, textvariable=self._var_ratio_1) self.ratio_1_input.grid(column=1, row=1) self.ratio_x_input = Entry(self, width=W_MATCH_RATIO, textvariable=self._var_ratio_x) self.ratio_x_input.grid(column=1, row=2) self.ratio_2_input = Entry(self, width=W_MATCH_RATIO, textvariable=self._var_ratio_2) self.ratio_2_input.grid(column=1, row=3) Button(self, text="Add", command=self._add_match).grid(column=2, row=1) Button(self, text="Clear", command=self._clear_inputs).grid(column=2, row=2) Button(self, text="Clear all", command=self._matches.clear).grid(column=2, row=3) for child in self.winfo_children(): child.grid_configure(padx=PAD_X, pady=PAD_Y, sticky=EW) def _clear_inputs(self): self._var_title.set("") self._var_ratio_1.set(0.0) self._var_ratio_x.set(0.0) self._var_ratio_2.set(0.0) self.title_input.focus() def _get_values(self) -> Optional[Tuple[str, float, float, float]]: try: return self._var_title.get(), self._var_ratio_1.get( ), self._var_ratio_x.get(), self._var_ratio_2.get() except Exception as ex: log.debug( f"Exception while getting manual matches input values: {ex}") messagebox.showerror("Invalid input", "Try again with different values!") return None def _add_match(self): match_details = self._get_values() if match_details: self._matches.add_match(*match_details) self._clear_inputs()