Search code examples
pythontkinterget

Tkinter: Reading int with get() from the window


I want to press any certain number into the window, then my submit output shall request the def lotto(anzahl): and give an output like: 4,20,40; if I enter 3 forex What exactly do I miss that anzahl is still not defined?

import Tkinter
window = Tkinter.Tk()
lot = Tkinter.Entry(window)
lot.pack()
anzahl = int(lot.get())
def lotto(anzahl):
    for i in range(anzahl):
        result_text = random.randint(1,45)
    tkMessageBox.showinfo("Result", result_text)
submit = Tkinter.Button(window, text="Submit", command=lambda:       lotto(anzahl))
submit.pack()
window.mainloop()

Solution

  • You will need to move anzahl = int(lot.get()) into your function if you want it to actively update with the button press. As it is now all you are doing is assigning an empty string because it only get() the value at the start.

    Take a look at the below code:

    import Tkinter
    import tkMessageBox
    import random
    
    window = Tkinter.Tk()
    lot = Tkinter.Entry(window)
    lot.pack()
    
    def lotto():
        anzahl = int(lot.get())
        for _ in range(anzahl):
            result_text = random.randint(1,45)
        tkMessageBox.showinfo("Result", result_text)
    
    submit = Tkinter.Button(window, text="Submit", command=lotto)
    submit.pack()
    window.mainloop()