Home > front end >  How to call event in entry when button or enter is pressed
How to call event in entry when button or enter is pressed

Time:03-18

I'm currently programming a math program. It has the features of starting, then displaying math questions until you answered 10 correctly, and then stopping. It works, but the user can only confirm their answer when they press a button (confirm()). This is really annoying. I wanted to make it so that it also activates if the user presses enter while in the entry field.

How to call an event if the user presses enter while their cursor is within the entry field?

# GUI
import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *

import gui2temp3_support

class spiel:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'
        self.style = ttk.Style()
        if sys.platform == "win32":
            self.style.theme_use('winnative')
        self.style.configure('.',background=_bgcolor)
        self.style.configure('.',foreground=_fgcolor)
        self.style.map('.',background=
            [('selected', _compcolor), ('active',_ana2color)])

        top.geometry("600x450 475 21")
        top.minsize(600, 450)
        top.maxsize(600, 450)
        top.resizable(0,0)
        top.title("Mathe-Skill-Programm Aktiv")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")
        top.bind('<Button-1><Button-1>',lambda e:gui2temp3_support.spiel(e))

        self.top = top

        self.Appname = tk.Label(self.top)
        self.Appname.place(relx=0.0, rely=0.0, height=51, width=604)
        self.Appname.configure(activebackground="#f9f9f9")
        self.Appname.configure(activeforeground="black")
        self.Appname.configure(background="#008080")
        self.Appname.configure(compound='left')
        self.Appname.configure(disabledforeground="#a3a3a3")
        self.Appname.configure(font="-family {Bahnschrift Light} -size 24 -weight bold")
        self.Appname.configure(foreground="#ffffff")
        self.Appname.configure(highlightbackground="#008080")
        self.Appname.configure(highlightcolor="black")
        self.Appname.configure(text='''Valentin's Lernprogramm''')

        self.Frame1 = tk.Frame(self.top)
        self.Frame1.place(relx=0.017, rely=0.133, relheight=0.856
                , relwidth=0.975)
        self.Frame1.configure(relief='groove')
        self.Frame1.configure(borderwidth="2")
        self.Frame1.configure(relief="groove")
        self.Frame1.configure(background="#d9d9d9")
        self.Frame1.configure(highlightbackground="#d9d9d9")
        self.Frame1.configure(highlightcolor="black")

        self.confirm = tk.Button(self.Frame1)
        self.confirm.place(relx=0.034, rely=0.26, height=44, width=197)
        self.confirm.configure(activebackground="#ececec")
        self.confirm.configure(activeforeground="#000000")
        self.confirm.configure(background="#008080")
        self.confirm.configure(command=gui2temp3_support.speichern)
        self.confirm.configure(compound='left')
        self.confirm.configure(disabledforeground="#a3a3a3")
        self.confirm.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.confirm.configure(foreground="#ffffff")
        self.confirm.configure(highlightbackground="#d9d9d9")
        self.confirm.configure(highlightcolor="black")
        self.confirm.configure(pady="0")
        self.confirm.configure(text='''Antwort bestätigen''')
        self.confirm.bind('<Button-1>',lambda e:gui2temp3_support.confirm(e))

        self.results = tk.LabelFrame(self.Frame1)
        self.results.place(relx=0.017, rely=0.39, relheight=0.584
                , relwidth=0.957)
        self.results.configure(relief='groove')
        self.results.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.results.configure(foreground="black")
        self.results.configure(text='''Resultate''')
        self.results.configure(background="#d9d9d9")
        self.results.configure(highlightbackground="#d9d9d9")
        self.results.configure(highlightcolor="black")

        self.zeit = tk.Label(self.results)
        self.zeit.place(relx=0.018, rely=0.133, height=21, width=284
                , bordermode='ignore')
        self.zeit.configure(activebackground="#f9f9f9")
        self.zeit.configure(activeforeground="black")
        self.zeit.configure(anchor='w')
        self.zeit.configure(background="#d9d9d9")
        self.zeit.configure(compound='left')
        self.zeit.configure(disabledforeground="#a3a3a3")
        self.zeit.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.zeit.configure(foreground="#000000")
        self.zeit.configure(highlightbackground="#d9d9d9")
        self.zeit.configure(highlightcolor="black")
        self.zeit.configure(text='''Zeit benötigt:''')

        self.score = tk.Label(self.results)
        self.score.place(relx=0.018, rely=0.222, height=21, width=244
                , bordermode='ignore')
        self.score.configure(activebackground="#f9f9f9")
        self.score.configure(activeforeground="black")
        self.score.configure(anchor='w')
        self.score.configure(background="#d9d9d9")
        self.score.configure(compound='left')
        self.score.configure(disabledforeground="#a3a3a3")
        self.score.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.score.configure(foreground="#000000")
        self.score.configure(highlightbackground="#d9d9d9")
        self.score.configure(highlightcolor="black")
        self.score.configure(text='''Score:''')

        self.nachricht = tk.Label(self.results)
        self.nachricht.place(relx=0.018, rely=0.8, height=21, width=534
                , bordermode='ignore')
        self.nachricht.configure(activebackground="#f9f9f9")
        self.nachricht.configure(activeforeground="black")
        self.nachricht.configure(anchor='w')
        self.nachricht.configure(background="#d9d9d9")
        self.nachricht.configure(compound='left')
        self.nachricht.configure(disabledforeground="#a3a3a3")
        self.nachricht.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.nachricht.configure(foreground="#000000")
        self.nachricht.configure(highlightbackground="#d9d9d9")
        self.nachricht.configure(highlightcolor="black")
        self.nachricht.configure(text= "Hallo, Lieber Benutzer!")

        self.temp_score = tk.Label(self.results)
        self.temp_score.place(relx=0.018, rely=0.311, height=21, width=244
                , bordermode='ignore')
        self.temp_score.configure(activebackground="#f9f9f9")
        self.temp_score.configure(activeforeground="black")
        self.temp_score.configure(anchor='w')
        self.temp_score.configure(background="#d9d9d9")
        self.temp_score.configure(compound='left')
        self.temp_score.configure(disabledforeground="#a3a3a3")
        self.temp_score.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.temp_score.configure(foreground="#000000")
        self.temp_score.configure(highlightbackground="#d9d9d9")
        self.temp_score.configure(highlightcolor="black")
        self.temp_score.configure(text='''Punkte:''')

        self.multiplier = tk.Label(self.results)
        self.multiplier.place(relx=0.018, rely=0.4, height=21, width=244
                , bordermode='ignore')
        self.multiplier.configure(activebackground="#f9f9f9")
        self.multiplier.configure(activeforeground="black")
        self.multiplier.configure(anchor='w')
        self.multiplier.configure(background="#d9d9d9")
        self.multiplier.configure(compound='left')
        self.multiplier.configure(disabledforeground="#a3a3a3")
        self.multiplier.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.multiplier.configure(foreground="#000000")
        self.multiplier.configure(highlightbackground="#d9d9d9")
        self.multiplier.configure(highlightcolor="black")
        self.multiplier.configure(text='''Multiplier:''')

        self.richtige_ant = tk.Label(self.results)
        self.richtige_ant.place(relx=0.018, rely=0.489, height=21, width=244
                , bordermode='ignore')
        self.richtige_ant.configure(activebackground="#f9f9f9")
        self.richtige_ant.configure(activeforeground="black")
        self.richtige_ant.configure(anchor='w')
        self.richtige_ant.configure(background="#d9d9d9")
        self.richtige_ant.configure(compound='left')
        self.richtige_ant.configure(disabledforeground="#a3a3a3")
        self.richtige_ant.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.richtige_ant.configure(foreground="#000000")
        self.richtige_ant.configure(highlightbackground="#d9d9d9")
        self.richtige_ant.configure(highlightcolor="black")
        self.richtige_ant.configure(text='''''')

        self.deine_ant = tk.Label(self.results)
        self.deine_ant.place(relx=0.018, rely=0.578, height=21, width=244
                , bordermode='ignore')
        self.deine_ant.configure(activebackground="#f9f9f9")
        self.deine_ant.configure(activeforeground="black")
        self.deine_ant.configure(anchor='w')
        self.deine_ant.configure(background="#d9d9d9")
        self.deine_ant.configure(compound='left')
        self.deine_ant.configure(disabledforeground="#a3a3a3")
        self.deine_ant.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.deine_ant.configure(foreground="#000000")
        self.deine_ant.configure(highlightbackground="#d9d9d9")
        self.deine_ant.configure(highlightcolor="black")
        self.deine_ant.configure(text='''''')

        self.xy = tk.Label(self.Frame1)
        self.xy.place(relx=0.034, rely=0.052, height=41, width=154)
        self.xy.configure(activebackground="#f9f9f9")
        self.xy.configure(activeforeground="black")
        self.xy.configure(anchor='w')
        self.xy.configure(background="#d9d9d9")
        self.xy.configure(compound='left')
        self.xy.configure(disabledforeground="#a3a3a3")
        self.xy.configure(font="-family {Segoe UI} -size 21 -weight bold")
        self.xy.configure(foreground="#000000")
        self.xy.configure(highlightbackground="#d9d9d9")
        self.xy.configure(highlightcolor="black")
        self.xy.configure(text='''x * y =''')

        self.antwort = tk.Entry(self.Frame1)
        self.antwort.place(relx=0.308, rely=0.052, height=50, relwidth=0.297)
        self.antwort.configure(background="white")
        self.antwort.configure(disabledforeground="#a3a3a3")
        self.antwort.configure(font="-family {Segoe UI} -size 21 -weight bold")
        self.antwort.configure(foreground="#000000")
        self.antwort.configure(highlightbackground="#d9d9d9")
        self.antwort.configure(highlightcolor="black")
        self.antwort.configure(insertbackground="black")
        self.antwort.configure(selectbackground="blue")
        self.antwort.configure(selectforeground="white")

        self.start_stop = tk.Button(self.Frame1)
        self.start_stop.place(relx=0.393, rely=0.26, height=44, width=197)
        self.start_stop.configure(activebackground="#ececec")
        self.start_stop.configure(activeforeground="#000000")
        self.start_stop.configure(background="#fc6d71")
        self.start_stop.configure(command=gui2temp3_support.speichern)
        self.start_stop.configure(compound='left')
        self.start_stop.configure(disabledforeground="#a3a3a3")
        self.start_stop.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.start_stop.configure(foreground="#ffffff")
        self.start_stop.configure(highlightbackground="#d9d9d9")
        self.start_stop.configure(highlightcolor="black")
        self.start_stop.configure(pady="0")
        self.start_stop.configure(text='''Start''')
        self.start_stop.bind('<Button-1>',lambda e:gui2temp3_support.start_stop(e))

        self.progress = ttk.Progressbar(self.Frame1)
        self.progress.place(relx=0.786, rely=0.052, relwidth=0.188, relheight=0.0
                , height=22)
        self.progress.configure(length="110")

        self.quit = tk.Button(self.Frame1)
        self.quit.place(relx=0.752, rely=0.26, height=44, width=117)
        self.quit.configure(activebackground="#ececec")
        self.quit.configure(activeforeground="#000000")
        self.quit.configure(background="#c10438")
        #self.quit.configure(command=gui2temp3_support.speichern)
        self.quit.configure(compound='left')
        self.quit.configure(disabledforeground="#a3a3a3")
        self.quit.configure(font="-family {Segoe UI} -size 9 -weight bold")
        self.quit.configure(foreground="#ffffff")
        self.quit.configure(highlightbackground="#d9d9d9")
        self.quit.configure(highlightcolor="black")
        self.quit.configure(pady="0")
        self.quit.configure(text='''Verlassen''')
        self.quit.bind('<Button-1>',lambda e:gui2temp3_support.quit(e))


def start_up():
    gui2temp3_support.main()

if __name__ == '__main__':
    gui2temp3_support.main()


Support Module:

import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
import time
import gui2temp3
from random import randint, choice

hex = ["1","2","3","4","5","6","7","8","9","0","A","B","C","D","E","F"]
nachrichtenfalsch = ['HAHAHA! DU VERLIERER! DEINE ANTWORT WAR KOMPLETT FALSCH HAHAHAA!', 'LOSER!!!', '0 IQ LOL', 'VERKACKT!', 'FALSCHE ANTWORT HAHAHHAA', '-99999999999999 SOCIAL CREDIT', 'MATHE GEHT BEI DIR WOHL NICHT, NE?', 'Deine Antwort war nicht richtig. Aber du musst jetzt nicht traurig sein, denn so etwas kann jedem mal passieren. Du bist immer noch so besonders fuer uns wie du es immer gewesen bist! Komm schon, vergiss den Zwischenfall und geb nicht auf!', '1x1 Zertifikat entzogen', 'NOOOOOOOB!', 'Du kannst besser fliegen als Matheaufgaben zu beantworten.', 'Mathematik scheint dir wohl nicht so zu liegen, LOL', 'Du kleiner Discord Mod, kannst noch nicht mal Matheaufgaben richtig beantworten.', 'Du dummer FETTSACK HAHAHA', 'INKORREKTE EINGABE HAHAHAA', 'irrefuehrende Rueckaeusserung einer primitiven Lebensform.', 'Du hast die Frage komplett Falsch beantwortet. Deswegen nehme ich dir jetzt einen Keks weg. HAHAHAHA']
nachrichtengut = ['Verdammt richtig man!', 'So was von korrekt!', 'Weiter so!', 'Deine Antwort war richtig!', 'SUPER!!!', 'Deine Antwort war richtig! Als Belohnung bekommst du einen Keks :)', 'DU BIST EIN GENIE!!', '101% Korrekt!', 'Richtig wie ein Glas mit Nutella!', 'Sie werden es noch einmal ganz weit bringen!', 'Als ich so alt war wie du haette ich das nie gekonnt!', 'Du kleines Wunderkind!']
death = 3
gestartet = False
time_start = time.time()
time1 = ""
correct_answer = ""
xmin = 2
xmax = 11
ymin = 1
ymax = 15
temp_start = None
c_answers = 0
w_answers = 0
s_answers = 0
score = 0
temp_score = 1
multiplier = 1
totaltime = 0
timestart = 0
timeend = 0
time_stop = 0
temp_end = None
fulltime = 0
temp_answers = 1
averangetime = 0
lowest_time = 0
worst_time = 0
time_wasted_total = 0
user_answer = ""

def main(*args):
    '''Main entry point for the application.'''
    global root
    root = tk.Tk()
    root.protocol( 'WM_DELETE_WINDOW' , root.destroy)
    # Creates a toplevel widget.
    global _top2, _w2
    _top2 = root
    _w2 = gui2temp3.spiel(_top2)
    root.mainloop()

def confirm(*args):
    global user_answer
    if gestartet is True:
        user_answer = _w2.antwort.get()
        _w2.nachricht.configure(foreground="#000000")
        _w2.antwort.delete(0, END)

        if str.isdecimal(user_answer) is False or user_answer == "":
            _w2.nachricht.configure(foreground="#FF0000")
            _w2.nachricht.configure(text="DU BIST EIN IDIOT!!! GIB ZAHLEN EIN, OK?!?!?")
        elif int(user_answer) == correct_answer:
            c_response()
            update()

        else:
            w_response()
    else:
        _w2.nachricht.configure(foreground="#FF0000")
        _w2.nachricht.configure(text="DU BIST EIN IDIOT!!! DAS PROGRAMM IS NOCH NICHTMAL GESTARTET!!")


def c_response():
    global totaltime, temp_score, lowest_time, worst_time, c_answers, temp_answers, score, multiplier, temp_end
    _w2.deine_ant.configure(text="")
    _w2.richtige_ant.configure(text="")
    _w2.nachricht.configure(text=choice(nachrichtengut))
    temp_end = time.time()
    c_answers  = 1
    temp_answers  = 1
    multiplier = 0.9   (0.1 * temp_answers)
    totaltime = temp_end - temp_start
    temp_score = round(multiplier / totaltime * 1000, 1)
    score  = temp_score
    _w2.temp_score.configure(text=f"Punkte:  {temp_score}")
    _w2.score.configure(text=f"Score: {score}")
    _w2.zeit.configure(text=f"Zeit benötigt: {round(totaltime,2)} Sekunden")
    _w2.multiplier.configure(text=f"Multiplier: {multiplier}")
    _w2.progress['value']  = 10
    if totaltime <= lowest_time:
        lowest_time = totaltime
        _w2.nachricht.configure(text=f"{choice(nachrichtengut)} (BESTZEIT!!)")
    elif lowest_time == 0:
        lowest_time = totaltime

    if totaltime >= worst_time:
        worst_time = totaltime
    if _w2.progress['value'] >= 100:
        start_stop()

def w_response():
    global totaltime, temp_score, time_wasted_total, w_answers, multiplier, temp_answers, user_answer
    w_answers  = 1
    temp_end = time.time()
    totaltime = temp_end - temp_start

    temp_answers = 1
    multiplier = 0.9   (0.1 * temp_answers)
    temp_score -= round(1000 * w_answers, 1)
    _w2.nachricht.configure(text=choice(nachrichtenfalsch))
    _w2.temp_score.configure(text=f"Punkte: {temp_score}")
    _w2.score.configure(text=f"Score: {score}")
    _w2.zeit.configure(text=f"Zeit verschwendet: {round(totaltime,2)} Sekunden")
    _w2.multiplier.configure(text=f"Multiplier: {multiplier}")
    _w2.richtige_ant.configure(text=f"Richtige Antwort: {correct_answer}")
    _w2.deine_ant.configure(text=f"Deine dumme Antwort: {user_answer}")

    temp_score = 0
def quit(*args):
    root.destroy()

def speichern(*args):
    return

def spiel(*args):
    print('gui2temp3_support.spiel')
    for arg in args:
        print ('another arg:', arg)
    sys.stdout.flush()
def update():
    global temp_start, correct_answer
    temp_start = time.time()
    x = randint(int(xmin), int(xmax))
    y = randint(int(ymin), int(ymax))
    _w2.xy.configure(text=f'''{x} * {y} =''')
    correct_answer = x * y
def start_stop(*args):
    global gestartet, correct_answer, temp_start, temp_end, time_stop
    if gestartet is False:
        _w2.start_stop.configure(text='''Stop''')
        _w2.start_stop.configure(background="#ffffff")
        _w2.start_stop.configure(foreground="#fc6d71")
        gestartet = True
        temp_start = time.time()
        update()

    elif gestartet is True:
        _w2.start_stop.configure(text='''Start''')
        _w2.start_stop.configure(background="#fc6d71")
        _w2.start_stop.configure(foreground="#ffffff")
        time_stop = time.time()
        gestartet = False
        zeit_antwort = time_stop - time_start
        _w2.xy.configure(text=f'''x * y =''')
        _w2.zeit.configure(text=f'''Zeit Gesamt: {round(zeit_antwort, 2)} Sekunden''')
        temp_start = 0
        temp_end = 0
        _w2.progress['value'] = 0
    elif _w2.progress['value'] >= 100:
        _w2.start_stop.configure(text='''Neustarten''')
        _w2.start_stop.configure(background="#fc6d71")
        _w2.start_stop.configure(foreground="#ffffff")
        time_stop = time.time()
        gestartet = False
        end_config()

def end_config():
        global time_start, time_stop
        zeit_antwort = time_stop - time_start
        _w2.xy.configure(text=f'''x * y =''')
        _w2.zeit.configure(text=f'''Zeit Gesamt: {round(zeit_antwort, 2)} Sekunden''')
        _w2.richtige_ant.configure(text=f"Richtige Antworten: {c_answers}")
        _w2.deine_ant.configure(text=f"Falsche Antworten: {w_answers}")

        _w2.multiplier.configure(text=f"Durchschnittszeit pro richtige Antwort: {round(zeit_antwort / c_answers, 2)}")


if __name__ == '__main__':
    gui2temp3.start_up()




CodePudding user response:

You bind the event to the widget in question. In the example below, '<Return>' is the key in question, and return_pressed is the name of the function or method it triggers when the key is pressed.

See this for some more details.

sidenote: you might also want to read up on bind_all

        self.antwort.bind('<Return>', return_pressed)
  • Related