1. 程式人生 > 其它 >使用Python tkinter寫一個簡單的按鍵遊戲

使用Python tkinter寫一個簡單的按鍵遊戲

技術標籤:tkinterpython遊戲gui

筆者也是剛入門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()

期待和大家交流!