猜数字小游戏
源码
import random
import tkinter
import sys
import tkinter.messagebox
def cai_shu_zi():
global i
if Button1[‘text’] == “游戏结束”:
sys.exit()
else:
try:
text_check = ‘’.join(j for j in Entry1.get() if j in ‘0123456789’)
int_cin = int(text_check)
if i == 5 and int_cin != n:
Label2[‘text’] = “你已经猜了5次了,并且都没有猜中”
Button1[‘text’] = “游戏结束”
Entry1.delete(0, ‘end’)
elif int_cin < n:
Label2[‘text’] = “你输入的数比较小”
i += 1
Button1[‘text’] = “输入下一个数字”
Entry1.delete(0, ‘end’)
elif int_cin > n:
Label2[‘text’] = “你输入的数比较大”
i += 1
Button1[‘text’] = “输入下一个数字”
Entry1.delete(0, ‘end’)
elif int_cin == n:
Label2[‘text’] = “恭喜你猜对了”
Button1[‘text’] = “游戏结束”
Entry1.delete(0, ‘end’)
except ValueError:
tkinter.messagebox.showerror(title=‘Error’, message=‘请输入数字’)
if name == “main”:
n = int(random.random() * 50 + 1)
i = 0
window = t

这是一个使用Python和Tkinter库编写的猜数字小游戏。玩家有五次机会猜测一个1到50之间的随机数,程序会提示玩家输入的数字是偏大还是偏小,直到猜中为止。
最低0.47元/天 解锁文章
741





