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

时间:2018-09-27 19:45:16

标签: python tkinter

我正在尝试用Pyhon tkinter进行“猜数字”游戏,但是到目前为止,我还无法从用户那里检索输入。

按下entry时如何在b1中获得输入?

我也想向玩家显示一条较低或较高的消息,但我不确定我所拥有的是否正确:

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)

3 个答案:

答案 0 :(得分:0)

您可以在get中定义main,以便可以访问预先创建的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)

答案 1 :(得分:0)

您已乱序组装了随机的代码行。例如,root.mainloop()只能在设置代码后被调用一次,但是您要在main()的中间调用它,以使之后的任何操作都不会执行,直到Tk被拆除为止。 while guess != randomnum:循环在事件驱动的代码中没有位置。无论是什么,实际上都应该在注释之前:

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

让我们采用一种更简单,更清洁的方法。除了使用指向各种小部件的指针外,我们还可以使用它们的textvariablecommand属性来运行显示并在设置后忽略小部件。我们将使用StringVarIntVar处理输入和输出。而且,我们将使用sleep()功能,而不是使用引发事件的after()

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

答案 2 :(得分:0)

这种方法的真正问题是结构不良的 tkinter

游戏可以在没有 tkinter 的情况下实现,就像这样。


import sys, random

def question():
    return round(random.randrange(100,10000)/100, 2 )

randomnum = question( )

while 1:
    guess = input( "WHAT NUMBER AM I THINKING OF" )
    if guess == "" or guess.upper() != guess.lower():
        test = input( "Do you wish to end game? Y|N" )
        if test.upper() == "Y":
            sys.stderr.write( "Game Over Man\n" )
            break
    elif guess.count(".") > 1:
        sys.stderr.write( "Erroneous value!!\nTry again\n" )
    else:
        guess = float( guess )
        if guess < randomnum:
            sys.stdout.write( "\nHigher!\n" )
        elif guess > randomnum:
            sys.stdout.write( "\nLower!\n" )
        else:
            sys.stderr.write( "\nGOT IT!!\n" )
            randomnum = question( )

但是,如果您想在 tkinter 中实现它,请尝试使用 class


import time
import random
import decimal
import tkinter as tk


def flexx( o, r = 0, c = 0, rw = 1, cw = 1 ):
    """flexx( o(TkContainer), r=0, c=0, rw=1, cw=1 )"""
    if r != None:
        o.rowconfigure( r, weight = rw )
    if c != None:
        o.columnconfigure( c, weight = cw )


class number_game:

    def __init__( self ):

        self.master = tk.Tk()
        flexx( self.master )
        flexx( self.master, r=1 )
        flexx( self.master, r=2 )

        self.guess = self.tries = self.total = 0

        self.entry = tk.Entry(
            self.master, width = 20, font = "Helvetic 20 normal" )
        self.entry.grid( row = 0, column = 0 )

        tk.Button(
            self.master, text="Take a Guess",
            command = self.play, width = 40 ).grid( row = 1, column = 0 )

        self.display = tk.Label( self.master, font = "Helvetic 15 italic" )
        self.display.grid( row = 2, column = 0 )
        self.choose( )

    def play( self ):

        self.guess = self.entry.get()
        if self.guess == "" or self.guess.upper() != self.guess.lower():
            self.display[ "text" ] = "You've had enough\nAfter {} games.".format( self.total )
            self.wait = self.master.after( 4000, self.closer )
        else:
            self.guess = float( self.guess )
            if self.guess < self.randomnum:
                self.tries += 1
                self.display[ "text" ] = "Higher!\nTries {}".format( self.tries )
            elif self.guess > self.randomnum:
                self.tries += 1
                self.display[ "text" ] = "Lower!\nTries {}".format( self.tries )
            else:
                self.display[ "text" ] = "Well guessed\nTries {}".format( self.tries )
                self.tries = 0
                self.wait = self.master.after( 3000, self.choose )
            self.total += 1
            self.entry.delete( "0", "end" )

    def choose( self ):
        self.randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)
        self.display[ "text" ] = "Choose a number\nTries {}".format( self.tries )
        self.entry.focus()

    def closer( self ):
        self.master.destroy()

if __name__ == "__main__":

    game = number_game()
    tk.mainloop( )