Skip to content Skip to sidebar Skip to footer

Get Input In Python Tkinter Entry When Button Pressed

I am trying to make a 'guess the number' game with Pyhon tkinter but so far I have not been able to retrieve the input from the user. How can I get the input in entry when b1 is pr

Solution 1:

You could define get inside main, so that you can access the entry widget you created beforehand, like this:

entry = tk.Entry()
    def get():
        guess = entry.get()
        return guess # Replace this with the actual processing.
    b1 = tk.Button(root, text="Guess", command=get)

Solution 2:

You've assembled random lines of code out of order. For example, the root.mainloop() should only be called once after setting up the code but you're calling it in the middle of main() such that anything after won't execute until Tk is torn down. And the while guess != randomnum: loop has no place in event-driven code. And this, whatever it is, really should be preceded by a comment:

randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)

Let's take a simpler, cleaner approach. Rather than holding onto pointers to the the various widgets, let's use their textvariable and command properties to run the show and ignore the widgets once setup. We'll use StringVar and IntVar to handle input and output. And instead of using sleep() which throws off our events, we'll use the after() feature:

import tkinter as tk
from random import randint

def get():
    number = guess.get()

    if number < random_number:
        hint.set("Higher!")
        root.after(1000, clear_hint)
    elif number > random_number:
        hint.set("Lower!")
        root.after(1000, clear_hint)
    else:
        hint.set("Well guessed!")
        root.after(5000, setup)

def setup():
    global random_number

    random_number = randint(1, 100)
    guess.set(0)
    hint.set("Start Guessing!")
    root.after(2000, clear_hint)

def clear_hint():
    hint.set("")

root = tk.Tk()

hint = tk.StringVar()
guess = tk.IntVar()

random_number = 0

tk.Entry(textvariable=guess).grid(column=0, row=0)
tk.Button(root, text="Guess", command=get).grid(column=1, row=0)
tk.Label(root, textvariable=hint).grid(column=0, row=1)

setup()

root.mainloop()

Solution 3:

Here is a tkinter version on the number guessing game.

while or after are not used!

Program checks for illegal input (empty str or words) and reports error message. It also keeps track of the number of tries required to guess the number and reports success with a big red banner.

I've given more meaningful names to widgets and used pack manager instead of grid.

You can use the button to enter your guess or simply press Return key.

import time
import random
import tkinter as tk

root = tk.Tk()
root.title( "The Number Guessing Game" )

count = guess = 0

label = tk.Label(root, text = "The Number Guessing Game", font = "Helvetica 20 italic")
label.pack(fill = tk.BOTH, expand = True)

def pick_number():
    global randomnum
    label.config( text = "I am tkinking of a Number", fg = "black" )
    randomnum = random.choice( range( 10000 ) )/100
    entry.focus_force()

def main_game(guess):
    global count
    count = count + 1
    entry.delete("0", "end")
    if guess < randomnum:
        label[ "text" ] = "Higher!"
    elif guess > randomnum:
        label[ "text" ] = "Lower!"
    else:
        label.config( text = f"CORRECT! You got it in {count} tries", fg = "red" )
        root.update()
        time.sleep( 4 )
        pick_number()
        count = 0

def get( ev = None ):
    guess = entry.get()
    if len( guess ) > 0 and guess.lower() == guess.upper():
        guess = float( guess )
        main_game( guess )
    else:
        label[ "text" ] = "MUST be A NUMBER"
        entry.delete("0", "end")
               

entry = tk.Entry(root, font = "Helvetica 15 normal")
entry.pack(fill = tk.BOTH, expand = True)
entry.bind("<Return>", get)
b1 = tk.Button(root, text = "Guess", command = get)
b1.pack(fill = tk.BOTH, expand = True)

pick_number()

root.geometry( "470x110" )
root.minsize( 470, 110 )

root.mainloop()

Post a Comment for "Get Input In Python Tkinter Entry When Button Pressed"