码迷,mamicode.com
首页 > 编程语言 > 详细

python猜数字GUI版本V0.2

时间:2019-01-30 00:17:30      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:button   ber   代码   __init__   ext   game   loop   create   from   

使用类方式编写猜数字游戏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

标签:button   ber   代码   __init__   ext   game   loop   create   from   

原文地址:https://www.cnblogs.com/lufay/p/10336308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!