笔者也是刚入门tkinter两天的小萌新,推荐莫烦的相关教学视频,时长较短而且讲得很清楚。
想到了史上最坑爹游戏的某一关,所以基于最基本的Label、Button、messagebox控件,复刻了一下,游戏主界面如下图所示。
游戏规则:点击蓝色按钮100次胜利,点到黄色按钮则失败。过程中两个按钮会随机交换位置,且随着剩余按键次数的减少,交换位置的概率提高。
Python版本:3.7.0
import tkinter as tk
import tkinter.messagebox
import random
window = tk.Tk()
window.title('Crazy Buttons')
window.geometry('250x120')
l = tk.Label(window, text = '点击蓝色按钮100次', font = ('Microsoft YaHei', 12))
l.place(x = 125, y = 30, anchor = 'center')
counter = 100
color = 1
is_retry = True
def blue():
global counter, color
counter -= 1
l.config(text = '点击蓝色按钮' + str(counter) + '次')
if random.random()*float(counter^3) < 0.5:
if color == 1:
b1.config(bg = 'Yellow', command = yellow)
b2.config(bg = 'Blue', command = blue)
else:
b1.config(bg = 'Blue', command = blue)
b2.config(bg = 'Yellow', command = yellow)
color = 1 - color
if counter == 0:
if is_retry == True:
tk.messagebox.showinfo(title = 'Congratulations!', message = '~~~ 你赢了!~~~')
else:
tk.messagebox.showinfo(title = 'Congratulations!', message = '恭喜你发现了成功的捷径!')
window.destroy()
def yellow():
global counter, is_retry
is_retry = tk.messagebox.askretrycancel(title = 'Sorry', message = '你输了!是否重新开始游戏?')
if is_retry == True:
counter = 100
l.config(text = '点击蓝色按钮100次')
b1.config(bg = 'Blue', command = blue)
b2.config(bg = 'Yellow', command = yellow)
b1 = tk.Button(window, bg = 'Blue', width = 7, height = 1, command = blue)
b1.place(x = 80, y = 70, anchor = 'center')
b2 = tk.Button(window, bg = 'Yellow', width = 7, height = 1, command = yellow)
b2.place(x = 170, y = 70, anchor = 'center')
window.mainloop()
期待和大家交流!