简体   繁体   English

将非 GUI 应用程序转换为 GUI 应用程序 (Python/Tkinker)

[英]Converting Non-GUI application to GUI application (Python/Tkinker)

I have created a non-GUI guessing game where the end user will "roll a dice" and then is asked to guess a number.我创建了一个非 GUI 猜谜游戏,最终用户将“掷骰子”,然后被要求猜一个数字。 The result of the 'dice roll" determines how may tries the end user gets to guess the number. Results of the game play is saved in a notepad.txt file and the notepad file is opened after gameplay. “掷骰子”的结果决定了最终用户猜数字的次数。游戏结果保存在 notepad.txt 文件中,并在游戏结束后打开记事本文件。

This code works 100% (NON GUI - SHELL/OUTPUT ONLY GAME)此代码 100% 有效(非 GUI - 仅外壳/输出游戏)

import random
import time
import sys
import os

print("Welcome to the guessing game")
time.sleep(1)
userName = input("please input your name ")
time.sleep(1)
print("hi", (userName), "let me tell you how to play")
time.sleep(1)
print("the aim of the game is to guess the number the computer is thinking about")
time.sleep(1)
print("the computer roles the dice, and the result is the your number of attempts")
time.sleep(1)
print("on every attempt, the computer will guess a new number")
time.sleep(1)
print("if you guess the number, you win")
time.sleep(1)
print("lets begin")
time.sleep(2)
print("rolling the dice..")
time.sleep(3)
randNum2 = random.randrange(1, 6)
print(randNum2)
tries = 0
correct = 0

count = randNum2
while not count == 0:
    input1 = int(input("guess a number 1,100 "))
    randNum1 = random.randrange(1, 100)
    if (input1 == randNum1):
        print("correct")
        correct += 1
        break
    else:
        print("incorrect")
        if input1 > randNum1:
            print("You guessed to high")
        else:
            print("you guessed to low")

        tries += 1
        print(randNum1)
        print(count - 1)
        count -= 1
print("computer", (tries), (userName), (correct))
from datetime import datetime

now = datetime.now()
d2 = now.strftime("%B %d, %Y %H:%M:%S")
orig_stdot = sys.stdout
f = open('statistics.txt', 'a')
sys.stdout = f
print("the computer won", (tries), "times", (userName), "won", (correct), "times ", d2)
f.close()
os.system("statistics.txt")

# statistics = input("whould you like to view the statistics?: ")
# if statistics == "yes":
# os.system("statistics.txt")

I have already passed this subject in my coding class.我已经在我的编码 class 中通过了这个主题。 However as I wish to gain a better understanding of coding so i am attempting to convert this non-gui game to gui (as a personal project).然而,由于我希望更好地理解编码,所以我试图将这个非 gui 游戏转换为 gui(作为个人项目)。 However, I am not finding it as simple.但是,我发现它并不简单。

this is the code of the GUI VERSION of the game;这是游戏GUI版本的代码;

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

# 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")
userNameEntry = tk.Entry(window)
userNameLabel.pack()
userNameEntry.pack()

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

diceResult = random.randrange(1, 6)


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

    print(diceResult)
    tries += diceResult


def takeGuess():
    global wins
    global losses
    global tries
    global diceResult
    global rannum
    count = diceResult
    while not count == 0:
        print(rannum)
        if (guess == rannum):
            print("correct")
            wins += 1
            print(wins)
            break

        else:
            print("incorrect")
            print("the number was:", (rannum))

            tries += 1
            count -= 1

    # GUI Buttons


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

guessButton = tk.Button(window, text="take guess", command=takeGuess)  # button will need a comand
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")  # 'statistics.txt' is not recognized as an internal or external command,


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

window.mainloop()

This is the output of the GUI Version of the number guessing game.这是GUI版的猜数字游戏的output。

User selects "guessButton" Tk.Button用户选择“guessButton”Tk.Button

"C:\Program Files\Python37\python.exe" "D:/Number Guess Game (GUI).py"
August 10, 2020 12:32:11
88
incorrect
the number was: 88
88
incorrect
the number was: 88
88
incorrect
the number was: 88

User selects "diceButton" tk.Button用户选择“diceButton”tk.Button

3

As you can see, "guessButton" runs the def function "throwDice", this function is not working and prints "incorrect (three times in a row) on every button click, even if the user guesses the number correctly, the output will always print "incorrect" three times in one row. As you can see, "guessButton" runs the def function "throwDice", this function is not working and prints "incorrect (three times in a row) on every button click, even if the user guesses the number correctly, the output will always连续打印三次“不正确”。

(the "diceButton" that runs the command "throwDice" is working as expected and displays a random.randrange) (运行命令“throwDice”的“diceButton”按预期工作并显示 random.randrange)

This is the output of the NON-GUI VERSION, I wish for the GUI version to match this output:这是 NON-GUI VERSION 的 output,我希望 GUI 版本与此 output 匹配:

"C:\Program Files\Python37\python.exe" "D:/NUmber Guess Game - ITCPRG301.py"
Welcome to the guessing game
please input your name Shane
hi Shane let me tell you how to play
the aim of the game is to guess the number the computer is thinking about
the computer roles the dice, and the result is the your number of attempts
on every attempt, the computer will guess a new number
if you guess the number, you win
lets begin
rolling the dice..
2
guess a number 1,100 90
incorrect
You guessed to high
27
1
guess a number 1,100 27
incorrect
you guessed to low
58
0
computer 2 Shane 0

If i can get past this road bump I should be able to program the application to display the results of the game within the GUI instead of the shell.如果我能克服这个障碍,我应该能够对应用程序进行编程,以在 GUI 中而不是 shell 中显示游戏结果。

Any advise will be appreciated.任何建议将不胜感激。

Input via a Entry widget is stored as a string .通过Entry小部件的输入存储为字符串 Try to explicitly typecast enterGuess using int() before comparing it to randNum1 .在与randNum1进行比较之前,尝试使用int()显式类型转换enterGuess

userGuessed = int(enterGuess.get())
...

if userGuess == randNum1:
    print('correct')
    ...

Let me know if this solves your problem.让我知道这是否可以解决您的问题。

Use the below as a base.使用以下内容作为基础。 I rewrote your entire thing with a class structure and proper PEP8.我用 class 结构和正确的 PEP8 重写了你的全部内容。 All the problems you had are solved.你遇到的所有问题都解决了。 Learn from this and build on top of it to finish your game.从中学习并在此基础上构建以完成您的游戏。

import tkinter as tk
import random, time

class App(tk.Tk):
    #width, height and title are constants of your app so, write them as such
    WIDTH  = 600
    HEIGHT = 500
    TITLE  = "Shane's Number Guessing Game"
    
    def __init__(self):
        tk.Tk.__init__(self)
        
        #init vars
        self.tries  = 0
        self.wins   = 0
        self.losses = 0
        self.roll   = 0
        self.rand   = 0
        
        tk.Label(self, text="please enter your name below").grid(column=0)
        self.name = tk.Entry(self)
        self.name.grid(column=0)
        
        tk.Label(self, text="enter guess below").grid(column=0)
        self.guess = tk.Entry(self, text='0')
        self.guess.grid(column=0)
        
        self.roll_btn = tk.Button(self, text="roll dice", command=self.roll_dice)
        self.roll_btn.grid(column=0)
        
        self.guess_btn = tk.Button(self, state='disabled', text="take guess", command=self.make_a_guess)
        self.guess_btn.grid(column=0)
        
        tk.Button(self, text="save stats", command=self.stats).grid(column=0)
        
        self.rand = random.randrange(1, 100)

    def reset(self):
        self.rand = random.randrange(1, 100)
        self.roll_btn['state']  = 'normal'
        self.guess_btn['state'] = 'disabled'
        
    def roll_dice(self):
        self.roll = random.randrange(1, 6)
        self.roll_btn['state']  = 'disabled'
        self.guess_btn['state'] = 'normal'
        
    def make_a_guess(self):
        if self.roll > 0:
            self.tries += 1
            self.roll  -= 1  
            print(self.rand)
            if int(self.guess.get()) == self.rand:
                self.wins += 1
                print(f'Correct! You have {self.wins} wins')
                self.reset()
            elif self.roll < 1:
                self.losses += 1
                print(f'Incorrect. The number was {self.rand}. You have {self.losses} losses')
                self.reset()
                
    def stats(self):
        timestamp = time.strftime("%B %d, %Y %H:%M:%S")
        msg = f'{timestamp}: {self.wins} wins and {self.losses} losses with {self.tries} tries\n'
        with open('statistics.txt', 'a') as f:
            f.write(msg)


#use proper PEP8 to initialize your program
if __name__ == "__main__":
    app = App()
    app.geometry(f'{App.WIDTH}x{App.HEIGHT}')
    app.title(App.TITLE)
    app.mainloop()

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

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