(Графический интерфейс игры в угадывание чисел) Получение тех же результатов с помощью команды (Python / Tkinter)

#python #tkinter

#python #tkinter

Вопрос:

Я получаю те же результаты при выполнении команды elif.

Это игра с угадыванием чисел (версия с графическим интерфейсом) цель игры состоит в том, чтобы пользователь ввел число от 1 до 100. Я пытаюсь получить Tk.Отображение метки, если пользователь угадал от высокого до низкого, используя команды elif.

Я включил функцию, с которой у меня возникли проблемы, вывод и полный код для программы в этом сообщении.

Функция

 def takeGuess():
    global wins
    global losses
    global tries
    global diceResult
    global rannum
    count = diceResult
    userGuess = int(enterGuess.get())
    while not count == 0:
        print(rannum)
        if userGuess == rannum:
            print("correct")
            wins  = 1
            correctLabel = tk.Label(window,text="correct")
            correctLabel.pack()
            break

        elif count <= rannum:
                print("incorrect, you guessed to low")
                print(count - 1)
                print("the number was:", (rannum))
                incorrectLabel = tk.Label(window, text="incorrect, you guessed to low")
                incorrectLabel.pack()

                tries  = 1
                count -= 1

                break

        elif count >= rannum:
                print("incorrect, you guessed to high")
                print(count - 1)
                print("the number was: ", (rannum))
                incorrectLabel = tk.Label(window, text="incorrect, you guessed to high")
                incorrectLabel.pack()

                tries  = 1
                count -= 1

                break
  

Вывод

 "C:Program FilesPython37python.exe" "E:/Shanes Number Guessing Game (GUI).py"
August 31, 2020 13:29:11
44
incorrect, you guessed to low
1
the number was: 44
44
incorrect, you guessed to low
1
the number was: 44
  

Весь код полностью

 import random
import tkinter as tk
import time
import sys
import datetime
import os


window = tk.Tk()
window.title("Shanes Number Guessing Game")
window.geometry("600x500")
window.configure(bg='#74eb34')

# GUI Image
#logo = tk.PhotoImage(file="C:Python-Tkinter pics\numberguess.png")
#photo1 = tk.Label(image=logo)
#photo1.image = logo
#photo1.pack()

# score
tries = 0
wins = 0

# user enters their username
userNameLabel = tk.Label(window, text="please enter your name below", bg='#74eb34', font='bold')
userNameEntry = tk.Entry(window)
name = str(userNameEntry.get())
userNameLabel.pack()
userNameEntry.pack()

def HiName():
    HiNameLabel = tk.Label(window,text="Gday "   str(userNameEntry.get())   "n"   "I want to play a game"   "n"   "roll the dice to get a number"   "n"   "The computer will then guess a number between 1-100"   "n"   "your dice number determines how many guesses you get"   "n"   "lets play" , bg='#74eb34')
    HiNameLabel.pack()

HiNameButton = tk.Button(window,text="record name", command=HiName)
HiNameButton.pack()

# User enters their guess in a entry box
enterGuessLabel = tk.Label(window, text="enter guess below", bg='#74eb34', font='bold')
enterGuessLabel.pack()
enterGuess = tk.Entry(window, text=0)
enterGuess.pack()

diceResult = random.randrange(1, 6)


# Throw dice
def throwDice():
    global diceResult
    global tries

    print(diceResult)
    diceLabel = tk.Label(window, text="the number of your dice is: "   str(diceResult),font="bold", bg='#74eb34')
    diceLabel.pack()
    tries  = diceResult


def takeGuess():
    global wins
    global losses
    global tries
    global diceResult
    global rannum
    count = diceResult
    userGuess = int(enterGuess.get())
    while not count == 0:
        print(rannum)
        if userGuess == rannum:
            print("correct")
            wins  = 1
            correctLabel = tk.Label(window,text="correct")
            correctLabel.pack()
            break

        elif count <= rannum:
                print("incorrect, you guessed to low")
                print(count - 1)
                print("the number was:", (rannum))
                incorrectLabel = tk.Label(window, text="incorrect, you guessed to low")
                incorrectLabel.pack()

                tries  = 1
                count -= 1

                break

        elif count >= rannum:
                print("incorrect, you guessed to high")
                print(count - 1)
                print("the number was: ", (rannum))
                incorrectLabel = tk.Label(window, text="incorrect, you guessed to high")
                incorrectLabel.pack()

                tries  = 1
                count -= 1

                break

    # GUI Buttons


diceButton = tk.Button(window, text="roll dice", command=throwDice)
diceButton.pack()

guessButton = tk.Button(window, text="take guess", command=takeGuess)
inputGuess = guessButton
guessButton.pack()

rannum = random.randrange(1, 100)

# Timestamp
timestamp = time.strftime("%B %d, %Y %H:%M:%S")
print(timestamp)


# open file
def file():
    os.system("statistics.txt")

def saveStats():
    with open("statistics.txt", "a") as output:
        output.write(str(userNameEntry.get())   " played a game on: "   time.strftime("%H:%M:%S %Y-%m-%d")   " and got the results: "   "n")


saveButton = tk.Button(window,text="Save Stats", command=saveStats)
saveButton.pack()

fileButton = tk.Button(window, text="open file", command=file)
fileButton.pack()

window.mainloop()
  

Комментарии:

1. elif count <= rannum: должно быть elif userGuess < rannum: и elif count >= rannum: должно быть elif userGuess > rannum: .

Ответ №1:

Я нашел свою проблему, мой код был правильным, но я допустил ошибку со своими переменными

Неверно

 while not count == 0:
    print(rannum)
    if count== rannum:
  

Правильно

 while not count == 0:
    print(rannum)
    if userGuess == rannum:
  

Ответ №2:

Вау! Сначала ваш вопрос смутил меня тем, что в таком хорошо написанном коде была эта ошибка, что при каждом запуске он всегда говорит, что вы угадали слишком низко. Вы проверяете свой код….. Вы допустили там глупую ошибку, смотрите (вместо userGuess вы написали count):

 elif  userGuess < rannum:
            print("incorrect, you guessed to low")
            print(count - 1)
            print("the number was:", (rannum))
            incorrectLabel = tk.Label(window, text="incorrect, you guessed to low")
            incorrectLabel.pack()

            tries  = 1
            count -= 1

            break

elif  userGuess > rannum:

        print("incorrect, you guessed to high")
        print(count - 1)
        print("the number was: ", (rannum))
        incorrectLabel = tk.Label(window, text="incorrect, you guessed to high")
        incorrectLabel.pack()

        tries  = 1
        count -= 1

        break
  

Ответ №3:

Немного улучшил вашу игру :

 import random
import tkinter as tk
import time
import sys
import datetime
import os


window = tk.Tk()
window.title("Shanes Number Guessing Game")
#window.geometry("600x500")
window.configure(bg='#74eb34')

# GUI Image
#logo = tk.PhotoImage(file="C:Python-Tkinter pics\numberguess.png")
#photo1 = tk.Label(image=logo)
#photo1.image = logo
#photo1.pack()

# score
tries = 0
wins = 0

# user enters their username
userNameLabel = tk.Label(window, text="please enter your name below", bg='#74eb34', font='bold')
userNameEntry = tk.Entry(window)
name = str(userNameEntry.get())
userNameLabel.pack()
userNameEntry.pack()

def HiName():
    HiNameLabel = tk.Label(window,text="Gday "   str(userNameEntry.get())   "n"   "I want to play a game"   "n"   "roll the dice to get a number"   "n"   "The computer will then guess a number between 1-100"   "n"   "your dice number determines how many guesses you get"   "n"   "lets play" , bg='#74eb34')
    HiNameLabel.pack()

HiNameButton = tk.Button(window,text="record name", command=HiName)
HiNameButton.pack()

# User enters their guess in a entry box
enterGuessLabel = tk.Label(window, text="enter guess below", bg='#74eb34', font='bold')
enterGuessLabel.pack()
enterGuess = tk.Entry(window, text=0)
enterGuess.pack()

diceResult = random.randrange(1, 6)


# Throw dice
def throwDice():
    global diceResult
    global tries

    print(diceResult)
    diceLabel = tk.Label(window, text="the number of your dice is: "   str(diceResult),font="bold", bg='#74eb34')
    diceLabel.pack()
    tries  = diceResult


def takeGuess():
    global wins
    global losses
    global tries
    global diceResult
    global rannum
    count = diceResult
    userGuess = int(enterGuess.get())
    while not count == 0:
        print(rannum)
        if userGuess == rannum:
            rannum = random.randrange(1, 100)
            print("correct")
            wins  = 1
            correctLabel = tk.Label(window,text="correct")
            correctLabel.pack()
            break

        elif userGuess < rannum:
                print("incorrect, you guessed to low")
                rannum = random.randrange(1, 100)
                print(count - 1)
                print("the number was:", (rannum))
                incorrectLabel = tk.Label(window, text="incorrect, you guessed to low ")
                lb = tk.Label(window, text = rannum).pack()
                incorrectLabel.pack()
                

                tries  = 1
                count -= 1

                break

        elif userGuess > rannum:
        
                print("incorrect, you guessed to high")
                rannum = random.randrange(1, 100)
                print(count - 1)
                print("the number was: ", (rannum))
                incorrectLabel = tk.Label(window, text="incorrect, you guessed to high ")
                lbd = tk.Label(window, text = rannum).pack()
                incorrectLabel.pack()

                tries  = 1
                count -= 1

                break

    # GUI Buttons


diceButton = tk.Button(window, text="roll dice", command=throwDice)
diceButton.pack()

guessButton = tk.Button(window, text="take guess", command=takeGuess)
inputGuess = guessButton
guessButton.pack()

rannum = random.randrange(1, 100)

# Timestamp
timestamp = time.strftime("%B %d, %Y %H:%M:%S")
print(timestamp)


# open file
def file():
    os.system("statistics.txt")

def saveStats():
    with open("statistics.txt", "a") as output:
        output.write(str(userNameEntry.get())   " played a game on: "   time.strftime("%H:%M:%S %Y-%m-%d")   " and got the results: "   "n")


saveButton = tk.Button(window,text="Save Stats", command=saveStats)
saveButton.pack()

fileButton = tk.Button(window, text="open file", command=file)
fileButton.pack()

window.mainloop()
  

Комментарии:

1. Этот ответ был бы лучше, если бы вы описали, что вы изменили. В противном случае нам придется сравнивать ваш код с исходным построчно и посимвольно.