Python 之GUI界面练手——tkinter猜数字小游戏
使用tkinter 的GUI界面制作的简单练手小游戏——猜数字。
初始情况
滑动滑块可调节随机数生成的范围。
输入猜测数字后点击试试看按钮,可出现提示框。
具体代码如下:
# 第1步,导入需要的库
import tkinter as tk
import tkinter.messagebox
import random
# 第2步,绘制GUI界面
root = tk.Tk()
root.title('猜数字小游戏:')#标题
root.geometry('300x160+500+200') # 这里的乘是小x
#第3步,创建第一个标题
l= tk.Label(root)
l.pack(side='top')
va2 = tk.StringVar()
def print_selection(v):
l.config(text='你选择的范围是1~' + v)
a = random.randint(1,int(v))
va2.set (a)
print (a)#测试用
# 第4步,创建一个尺度滑条,长度300字符,从1开始10结束,以1为刻度,精度为1.0,触发调用print_selection函数
s = tk.Scale(root, label='滑动我', from_=1, to=10, orient=tk.HORIZONTAL, length=300, showvalue=0,tickinterval=1, resolution=1.0, command=print_selection)
s.pack()
#第5步,创建填字区域
va1 = tk.StringVar()
ea1=tk.Entry(root, textvariable=va1,width = 16,bg = 'Pink')
ea1.pack()
#第6步,定义按钮功能,并创建按钮
def hit_me():
a = va1.get()
print (a)#测试用
b = va2.get()
print(b)#测试用
if a == b:
tk.messagebox.showinfo(title='Hi', message='猜对了!')
elif a < b:
tk.messagebox.showinfo(title='Hi', message='猜小了!')
else :
tk.messagebox.showinfo(title='Hi', message='猜大了!')
x = tk.Button(root, text='试试看', bg='black', fg='white', command=hit_me)
x.pack()
#第7步,循环显示GUI界面
tk.mainloop()在这里插入代码片