简体   繁体   English

Python Tkinter:我不确定如何将猜测输入与问题对齐

[英]Python Tkinter: I'm not sure how to align the guess input with the question

For this code, I'm trying to make a quiz game that has the user convert hexadecimal to decimal.对于这段代码,我正在尝试制作一个让用户将十六进制转换为十进制的问答游戏。 My only issue is that it's always a hexadecimal behind.我唯一的问题是它后面总是一个十六进制数。 To clarify, when I press enter to start the game, it turns the enter (which is blank) into a guess for the first hexadecimal.澄清一下,当我按回车键开始游戏时,它会将回车键(空白)变成对第一个十六进制数的猜测。

The code is originally from the Color game tutorial from geeksforgeeks, but I've changed it up to make it work for my Hex game.该代码最初来自 geeksforgeeks 的 Color 游戏教程,但我对其进行了更改以使其适用于我的 Hex 游戏。 In the color game though, it uses an array and it shuffles the color after the first run so it essentially aligns itself.但在颜色游戏中,它使用一个数组,并在第一次运行后打乱颜色,因此它基本上会自行对齐。

Here's my code:这是我的代码:

# import the modules
import tkinter
import random
from random import randint

# hex converter
conversionTable = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
    'F'
]


def decimalToHexadecimal(decimal):
    hexadecimal = ''
    while (decimal > 0):
        remainder = decimal % 16
        hexadecimal = conversionTable[remainder] + hexadecimal
        decimal = decimal // 16
    return hexadecimal  # return hexadecimal to main

# Other version of hex converter
# def gen_hex():
    # hex() - converts random number into the corresponding hex string
    # randint(0,255) - generates random int value between 0-255
    # [2:] - removes 0x from the resulting string
    rand_hex_str = hex(randint(0, 256))[2:]
    # retuns hex value
   # return rand_hex_str


# the score
score = 0

# the game time left, initially 30 seconds.
timeleft = 160

# function that will start the game.


def onEnter(event):
    label.config(text="You entered!")
    startGame()


def startGame():

    if timeleft == 160:

        # starts the countdown timer.
        countdown()

    # run the function to
    # choose the next numer
    nextNumber()


# Function to choose and
# display the next number


def nextNumber():

    # use the globally declared 'score'
    # and 'play' variables above.
    global score
    global timeleft

    # Utilizes the function to convert number to hex
    decimalNumber = random.randint(0, 255)
    hexNumber = decimalToHexadecimal(decimalNumber)

    # if the game is on
    if timeleft > 0:

        # makes the text entry box active
        e.focus_set()

        # debug code
        guess = e.get()
        print('decimal: ' + str(decimalNumber))
        print('guess: ' + str(guess))
        if guess == str(decimalNumber):
            score += 1

        # clear the text entry box.
        e.delete(0, tkinter.END)

        # changes the number
        label.config(text=hexNumber)

        # updates the score.
        scoreBoard.config(text="Score: " + str(score))


# Countdown timer function
def countdown():

    global timeleft

    # if a game is in play
    if timeleft > 0:

        # decrements the timer
        timeleft -= 1

        # update the time left label
        timeLabel.config(text="Time left: "
                         + str(timeleft))

        # run the function again after 1 second.
        timeLabel.after(1000, countdown)


# Background code
# creates a GUI window
root = tkinter.Tk()

# set the title of window
root.title("HEX GAME")

# set the window size
root.geometry("450x200")

# intro, hopefully it works
intro = """Welcome to the Hexadecimal Game! \n You will be given a point for every hexadecimal you get right and one point
deducted if wrong.
Press enter to start."""

# instructions label
instructions = tkinter.Label(root, text="The main objective is to determine "
                             "the decimal of the hexadecimal value that is given.",
                             font=('Helvetica', 12))
instructions.pack()

# scoreboard
scoreBoard = tkinter.Label(root, text=intro,
                           font=('Helvetica', 12))
scoreBoard.pack()

# add a time left label
timeLabel = tkinter.Label(root, text="Time left: " +
                          str(timeleft), font=('Helvetica', 12))

timeLabel.pack()

# add a label for displaying the numbers
label = tkinter.Label(root, font=('Helvetica', 60))
label.pack()

# text entry box for text
e = tkinter.Entry(root)

# runs the 'startGame' function when enter is pressed
root.bind('<Return>', onEnter)
e.pack()

# sets focus on the entry box
e.focus_set()

# starts the GUI
root.mainloop()

So originally, my root.bind was:所以最初,我的 root.bind 是:

root.bind('<Return>',startGame)

And I thought my code revision above would be able to stop the hexadecimal from immediately running after entering, but it didn't do anything.而且我认为我上面的代码修改可以阻止十六进制输入后立即运行,但它没有做任何事情。 I've also created a "guess = tkinter.Entry(root)" and switched all the "e.[function]"'s in my nextNumber() function to "guess.[function]" thinking it would differentiate from the "Press to Enter" entry box but it just broke the game.我还创建了一个“guess = tkinter.Entry(root)”并将我的 nextNumber() function 中的所有“e.[function]”切换为“guess.[function]”,认为它会与“按进入”输入框,但它刚刚打破了游戏。 I've tried both hex converters, tried taking out the if loop and putting a while loop with a set amount of turns, tried taking out the timer entirely, along with placing the random.randint() function in different places to see if it would stop the hexadecimal from immediately starting after entering, but nada.我已经尝试了两个十六进制转换器,尝试取出 if 循环并放置一个具有一定圈数的 while 循环,尝试完全取出计时器,并将 random.randint() function 放在不同的地方以查看它是否会阻止十六进制在输入后立即开始,但是 nada. Is there any way I can make sure the guess matches with its current hexadecimal question?有什么办法可以确保猜测与其当前的十六进制问题匹配吗?

The main issue was trying to check guess at the same time the number was being initialized.主要问题是试图在初始化数字的同时检查猜测。 Guess at that time is blank.当时的猜测是一片空白。

NextNumber is essentially an interface initialization. NextNumber 本质上是一个接口初始化。

I added a button check_answer.我添加了一个按钮 check_answer。 Attached to the value is a command = do_check.附加到该值的是命令 = do_check。 The command is what is called a callback function.该命令就是所谓的回调 function。

A GUI is an event-driven interface. GUI 是事件驱动的界面。 Clicking the button generates an event that calls the function to do the computations.单击该按钮会生成一个调用 function 进行计算的事件。

An alternative approach would have been to use events triggered by the entry box.另一种方法是使用由输入框触发的事件。 But that would add additional complexity.但这会增加额外的复杂性。

I do not know what resources you have.我不知道你有什么资源。 You might find python-course.eu useful.您可能会发现python-course.eu很有用。 Tkinter - the Python interface for Tk . Tkinter - Tk 的 Python 接口

Some comments and prints are added in the code, which I hope will help.代码中添加了一些注释和打印,希望对大家有所帮助。 I suggest you go through the answer code in your development environment, clean up, and add comments to help you understand what is happening.我建议你 go 通过答案代码在你的开发环境中清理,并添加注释以帮助你了解发生了什么。

# import the modules
import random
import tkinter

# hex converter
conversionTable = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
    'F'
]


def decimalToHexadecimal(decimal):
    hexadecimal = ''
    while (decimal > 0):
        remainder = decimal % 16
        hexadecimal = conversionTable[remainder] + hexadecimal
        decimal = decimal // 16
    return hexadecimal  # return hexadecimal to main

    # Other version of hex converter
    # def gen_hex():
    # hex() - converts random number into the corresponding hex string
    # randint(0,255) - generates random int value between 0-255
    # [2:] - removes 0x from the resulting string
    # rand_hex_str = hex(randint(0, 256))[2:]
    # returns hex value


# return rand_hex_str


# the score
score = 0

# the game time left, initially 30 seconds.
timeleft = 160
decimalNumber = 0  # store the decimal equivalent of a HEX number


# function that will start the game.


def onEnter(event):
    label.config(text="You entered!")
    startGame()


def startGame():
    if timeleft == 160:
        # starts the countdown timer.
        countdown()

    # run the function to
    # choose the next numer
    nextNumber()


# Function to choose and
# display the next number


def nextNumber():
    print('def nextNumber(): is initializing the GUI interface.')
    # use the globally declared 'score'
    # and 'play' variables above.
    global score
    global timeleft
    global decimalNumber
    # Utilizes the function to convert number to hex
    decimalNumber = random.randint(0, 255)
    hexNumber = decimalToHexadecimal(decimalNumber)

    # if the game is on
    if timeleft > 0:
        # makes the text entry box active
        e.focus_set()
        print('So guess = e.get() is empty at initialization')
        # debug code
        guess = e.get()
        print('decimal: ' + str(decimalNumber))
        print('guess: ' + str(guess))
        # if guess == str(decimalNumber):
        #     score += 1

        # clear the text entry box.
        e.delete(0, tkinter.END)

        # changes the number
        label.config(text=hexNumber)
        #
        # # updates the score.
        # scoreBoard.config(text="Score: " + str(score))


def do_check():
    """Checks an entry against the provided global decimalNumber"""
    global score
    # debug code
    guess = e.get()
    print('decimal: ' + str(decimalNumber))
    print('guess: ' + str(guess))
    if guess == str(decimalNumber):
        score += 1
    else:
        score -= 1
    # clear the text entry box.
    e.delete(0, tkinter.END)
    # updates the score.
    scoreBoard.config(text="Score: " + str(score))
    nextNumber()


# Countdown timer function
def countdown():
    global timeleft

    # if a game is in play
    if timeleft > 0:
        # decrements the timer
        timeleft -= 1

        # update the time left label
        timeLabel.config(text="Time left: "
                              + str(timeleft))

        # run the function again after 1 second.
        timeLabel.after(1000, countdown)


# Background code
# creates a GUI window
root = tkinter.Tk()

# set the title of window
root.title("HEX GAME")

# set the window size
root.geometry("450x300")

# intro, hopefully it works
intro = """Welcome to the Hexadecimal Game! \n You will be given a point for every hexadecimal you get right and one point
deducted if wrong.
Press enter to start."""

# instructions label
instructions = tkinter.Label(root, text="The main objective is to determine "
                                        "the decimal of the hexadecimal value that is given.",
                             font=('Helvetica', 12))
instructions.pack()

# scoreboard
scoreBoard = tkinter.Label(root, text=intro,
                           font=('Helvetica', 12))
scoreBoard.pack()

# add a time left label
timeLabel = tkinter.Label(root, text="Time left: " +
                                     str(timeleft), font=('Helvetica', 12))

timeLabel.pack()

# add a label for displaying the numbers
label = tkinter.Label(root, font=('Helvetica', 60))
label.pack()
check_answer = tkinter.Button(root, text="Click to check enter",
                              command=do_check, )
check_answer.pack()
# text entry box for text
e = tkinter.Entry(root)

# runs the 'startGame' function when enter is pressed
root.bind('<Return>', onEnter)
e.pack()

# sets focus on the entry box
e.focus_set()

# starts the GUI
root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM