按下按钮时,在Python tkinter条目中获取输入

fkaflof6  于 2023-02-11  发布在  Python
关注(0)|答案(4)|浏览(177)

我试图使一个'猜数字'游戏与Pyhon tkinter,但到目前为止,我还无法检索输入的用户。
按下b1时,如何获得entry中的输入?
我也想显示一个更低或更高的消息作为玩家的线索,但我不确定我所拥有的是否正确:

import time
import random
import decimal
import tkinter as tk

root = tk.Tk()

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

def get(entry):
    guess = entry.get()
    return guess

def main():
    b1 = tk.Button(root, text="Guess", command=get)
    entry = tk.Entry()
    b1.grid(column=1, row=0)
    entry.grid(column=0, row=0)
    root.mainloop()
    print(guess)
    if guess < randomnum:
        l2 = tk.Label(root, text="Higher!")
        l2.grid(column=0, row=2)
    elif guess > randomnum:
        l3 = tk.Label(root, text="Lower!")
        l3.grid(column=0, row=2)

while guess != randomnum:
    main()
l4 = tk.Label(root, text="Well guessed")
time.sleep(10)
piah890a

piah890a1#

您可以在main中定义get,以便访问之前创建的entry小部件,如下所示:

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

xqkwcwgp2#

你乱序地组合了一行随机代码。例如,root.mainloop()应该只在设置代码后被调用一次,但你却在main()的中间调用它,这样之后的任何东西都不会执行,直到Tk被删除。while guess != randomnum:循环在事件驱动代码中没有位置。不管它是什么,它确实应该在前面加上一个注解:

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

让我们采用一种更简单、更简洁的方法,我们不使用指向各种小部件的指针,而是使用它们的textvariablecommand属性来运行show,并在设置后忽略这些小部件,我们将使用StringVarIntVar来处理输入和输出,我们将使用after()特性,而不是使用会抛出事件的sleep()

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

dgjrabp23#

这里是一个tkinter版本的数字猜谜游戏。
未使用whileafter
程序检查非法输入(空字符串或单词)并报告错误信息。它还记录猜测数字所需的尝试次数,并用大红横幅报告成功。
我为小部件指定了更有意义的名称,并使用pack管理器而不是grid
您可以使用按钮输入您的猜测或只需按回车键。

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

4dbbbstv4#

正确的猜测数书写方式。

  • 我在get_number()函数中用Python编写了一个数字猜谜游戏的小脚本。
  • 使用一个小部件更新Label,而不是复制。
  • 我加了一些额外的圈数,你进入。

修改代码:

import time
import random
import decimal
import tkinter as tk

root = tk.Tk()

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

WIN = False
GUESS = 0
TURNS = 0

Vars = tk.StringVar(root) 

def get_number():
    global TURNS
    while WIN == False:
        Your_guess = entry.get()
        
        if randomnum == float(Your_guess):
            guess_message = f"You won!"             
            l3.configure(text=guess_message)
           
            number_of_turns = f"Number of turns you have used: {TURNS}"
            l4.configure(text=number_of_turns)
            l4.grid(column=0, row=3, columnspan=3, pady=5)
            
            WIN == True
            break
        else:
            if randomnum > float(Your_guess):
                guess_message = f"Your Guess was low, Please enter a higher number"                 
            else:
                guess_message = f"your guess was high, please enter a lower number"
                
        l3.configure(text=guess_message)
        l3.grid(column=0, row=2, columnspan=3, pady=5)
        TURNS +=1        
        return Your_guess

label = tk.Label(root, text="The Number Guessing Game", font="Helvetica 12 italic")
label.grid(column=0, row=0, columnspan=3, sticky='we')

l2 = tk.Label(root, text='Enter a number between 1 and 100',
              fg='white', bg='blue')
l2.grid(row=1, column=0, sticky='we')

entry = tk.Entry(root, width=10, textvariable=Vars)
entry.grid(column=1, row=1, padx=5,sticky='w')

b1 = tk.Button(root, text="Guess", command=get_number)    
b1.grid(column=1, row=1, sticky='e', padx=75) 

l3 = tk.Label(root, width=40, fg='white', bg='red' )
 
l4 = tk.Label(root, width=40, fg='white', bg='black' )
 

root.mainloop()

while guess:         
    time.sleep(10)

输入浮点数的输出:

猜测后的输出较高:

猜测后的输出较低:

你赢得的输出和圈数:

相关问题