1. 程式人生 > >(10)用tkinter模組寫簡易轉盤抽獎遊戲

(10)用tkinter模組寫簡易轉盤抽獎遊戲

實現轉盤抽獎需要再開一個執行緒,要用到threading庫,執行程式如下圖所示

這裡寫圖片描述

一個執行緒用來迴圈顯示面板,一個迴圈用來實現轉盤的迴圈

具體程式碼如下(程式碼在linux系統下pycharm中書寫)

import tkinter
# 匯入執行緒模組
import threading
import time

root = tkinter.Tk()
root.title('轉盤抽獎')
root.minsize(290,370)


# 擺放按鈕
btn1 = tkinter.Button(root, text = '藍芽耳機', bg = 'red')
btn1.place(x = 20, y = 20
, width = 70, height = 70) btn2 = tkinter.Button(root, text = '再來一次', bg = 'white') btn2.place(x = 110, y = 20, width = 70, height = 70) btn3 = tkinter.Button(root, text = '抱枕', bg = 'white') btn3.place(x = 200, y = 20, width = 70, height = 70) btn4 = tkinter.Button(root, text = '謝謝惠顧', bg = 'white') btn4.place(x = 20
, y = 110, width = 70, height = 70) btn5 = tkinter.Button(root, text = '保溫杯', bg = 'white') btn5.place(x = 200, y = 110, width = 70, height = 70) btn6 = tkinter.Button(root, text = '充電寶', bg = 'white') btn6.place(x = 20, y = 200, width = 70, height = 70) btn7 = tkinter.Button(root, text = 'iphoneX', bg = 'white'
) btn7.place(x = 110, y = 200, width = 70, height = 70) btn8 = tkinter.Button(root, text = '謝謝惠顧', bg = 'white') btn8.place(x = 200, y = 200, width = 70, height = 70) # 將所有選項組成列表 prizelists = [btn1,btn2,btn3,btn5,btn8,btn7,btn6,btn4] # 是否開啟迴圈的標誌 isloop = False # 是否執行的標誌 functions = False def round(): # 判斷是否開始迴圈(防止多次按下開始按鈕程式開啟多次轉盤迴圈) if isloop == True: return # 初始化計數變數 i = 0 while True: # 延時操作 time.sleep(0.06) # 將所有元件的背景顏色變為白色 for j in prizelists: j['bg'] = 'white' # 將當前數值對應的元件變色 prizelists[i]['bg'] = 'red' i += 1 # 如果i大於最大索引直接歸零 if i >= len(prizelists): i = 0 if functions == True: continue else: break # 建立一個新執行緒的函式 def newtask(): global isloop global functions # 建立執行緒 t = threading.Thread(target = round) # 開啟執行緒執行 t.start() # 設定迴圈開始標誌 isloop = True # 是否執行的標誌 functions = True # 定義停止迴圈的函式 def stop(): global isloop global functions functions = False isloop = False # 開始按鈕 btn_start = tkinter.Button(root, text = '開始', command = newtask) btn_start.place(x = 80, y = 300, width = 50, height = 50) # 結束按鈕 btn_stop = tkinter.Button(root, text = '結束', command = stop) btn_stop.place(x = 150, y = 300, width = 50, height = 50) root.mainloop()