且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按下按钮时在 Python tkinter Entry 中获取输入

更新时间:2023-12-03 20:39:52

这是一个关于猜数字游戏的 tkinter 版本.

Here is a tkinter version on the number guessing game.

whileafter 不使用!

程序检查非法输入(空字符串或单词)并报告错误信息.它还跟踪猜测数字所需的尝试次数,并用一个大红色横幅报告成功.

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.

我为小部件赋予了更有意义的名称,并使用了 pack 管理器而不是 grid.

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()