猜数字gui版本(1)

import tkinter as t
import random
from tkinter import messagebox

class app:
    def __init__(self, root):
        self.rec_text = t.StringVar()
        root.geometry('400x200')
        t.Button(root, text="点击生成随机数", command=self.change).pack(pady=20,anchor='center')
        root.mainloop()

    def change(self):
        global i
        i = 0
        self.n = int(random.random()*50+1)
        label1 = t.Label(root, text='你有5次猜测的机会:').pack(ipady=0, ipadx=0, padx=5, pady=10,anchor='center')
        self.entry = t.Entry(root, width=10,textvariable=self.rec_text)
        self.entry.pack(anchor='center')
        self.entry.focus()   #输入框自动获得焦点
        t.Button(root, text='查看结果', command=self.test).pack()
    def test(self):
        global i
        i = i + 1
        try:
            if self.n == int(self.rec_text.get()) and i <= 5:
                t.messagebox.showinfo(title='结果:', message='猜对了!')
            elif self.n > int(self.rec_text.get()) and i < 5:
                t.messagebox.showinfo(title='结果:', message=f'你猜的数字小了,还有{5-i}次机会')
            elif self.n < int(self.rec_text.get()) and i < 5:
                t.messagebox.showinfo(title='结果:', message=f'你猜的数字大了,还有{5-i}次机会')
            else:
                t.messagebox.showinfo(title='结果:', message='猜错了!机会已用完!')
        except:
            t.messagebox.showinfo(title='结果:', message='请输入正确的数字')

root = t.Tk()
app(root)
<__main__.app at 0x159312e2ef0>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值