python猜数字GUI版本V0.2
Posted lufay
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python猜数字GUI版本V0.2相关的知识,希望对你有一定的参考价值。
使用类方式编写猜数字游戏GUI版本。
思路:初始化数字以及初始化wegdits,编写button click event判断代码的函数,每猜一次点击button调用一次该函数,并计算猜的次数。如果猜对则显示次数。
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 07:36:46 2019
@author: pelu
"""
from tkinter import *
import random
class Application:
def __init__(self, master):
self.master = master
master.title("Guess Number Game")
self.random_number = random.randint(1, 100)
print(self.random_number)
self.tries = 0
self.label = Label(master, text="""
I‘m thinking of a number between 1 and 100.
Take a guess!
""")
self.label.pack()
self.lbl_result = Label(master, text="Good luck!")
self.lbl_result.pack()
self.user_guess = Entry(master, width=5)
self.user_guess.pack()
self.user_guess.focus()
self.greet_button = Button(master, text="Submit", command=lambda: self.check())
self.greet_button.pack()
def check(self):
user_number = self.user_guess.get()
player_guess = int(user_number)
if player_guess == self.random_number:
self.tries += 1
msg = "You win! You got it in " + str(self.tries) + " tries!"
self.lbl_result["text"] = msg
elif player_guess < self.random_number:
self.tries += 1
msg = "You are too low!"
self.lbl_result["text"] = msg
else:
self.tries += 1
msg = "You are too high!"
self.lbl_result["text"] = msg
root = Tk()
root.geometry("450x300")
my_gui = Application(root)
root.mainloop()
以上是关于python猜数字GUI版本V0.2的主要内容,如果未能解决你的问题,请参考以下文章