使用Python tkinter写一个简单的按键游戏

笔者也是刚入门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()

期待和大家交流!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值