Python開發轉盤小遊戲
Python開發轉盤小遊戲
Python
一 原理分析
- Python開發一個圖形界面
- 有12個選項和2個功能鍵
- 肯定每一個按鈕的位置
每一個按鈕的間隔相同
- 點擊開始時轉動,當前選項的背景顏色爲紅色,其餘爲白色
二 知識點與難點
2.1 使用的package
- tkinter
Python內置,實現GUI的主要package
- threading
實現多線程實現循環
- time
用來延時
2.2 注意點
- 判斷類型時使用isinstance函數,不要用type,由於type不區分子類
- 判斷變量是否爲TRUE,FALSE,None時要用is不要用==
- 循環時記得處理自增時超過下標時的歸零
- tkinter下面的按鈕屬性能夠經過鍵值賦值改變屬性
- 全局變量
三 代碼
- import tkinter
- import threading
- import time
-
- root = tkinter.Tk()
-
-
- root.title('香港男神')
-
-
- root.minsize(300, 300)
-
-
- btn1 = tkinter.Button(root, text='成龍', bg='red')
- btn1.place(x=20, y=20, width=50, height=50)
-
- btn2 = tkinter.Button(root, text='張國榮', bg='white')
- btn2.place(x=90, y=20, width=50, height=50)
-
- btn3 = tkinter.Button(root, text='郭富城', bg='white')
- btn3.place(x=160, y=20, width=50, height=50)
-
- btn4 = tkinter.Button(root, text='黎明', bg='white')
- btn4.place(x=230, y=20, width=50, height=50)
-
- btn5 = tkinter.Button(root, text='劉德華', bg='white')
- btn5.place(x=230, y=90, width=50, height=50)
-
- btn6 = tkinter.Button(root, text='梁朝偉', bg='white')
- btn6.place(x=230, y=160, width=50, height=50)
-
- btn7 = tkinter.Button(root, text='張學友', bg='white')
- btn7.place(x=230, y=230, width=50, height=50)
-
- btn8 = tkinter.Button(root, text='周潤發', bg='white')
- btn8.place(x=160, y=230, width=50, height=50)
-
- btn9 = tkinter.Button(root, text='周星馳', bg='white')
- btn9.place(x=90, y=230, width=50, height=50)
-
- btn10 = tkinter.Button(root, text='謝霆鋒', bg='white')
- btn10.place(x=20, y=230, width=50, height=50)
-
- btn11 = tkinter.Button(root, text='張家輝', bg='white')
- btn11.place(x=20, y=160, width=50, height=50)
-
- btn12 = tkinter.Button(root, text='古天樂', bg='white')
- btn12.place(x=20, y=90, width=50, height=50)
-
-
- herolist = [btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11, btn12]
-
-
- isloop = False
-
-
- isstop = False
-
-
- stopid = None
-
-
- def round():
-
-
- global isloop
- global stopid
-
-
- i = 1
-
-
- if isloop is True:
- return
-
- if isinstance(stopid, int):
- i = stopid
-
-
- while True:
-
-
- time.sleep(0.03)
-
-
-
- for e_btn in herolist:
- e_btn['bg'] = 'white'
-
-
- herolist[i]['bg'] = 'red'
-
- i += 1
- print('當前i爲', i)
-
-
- if i >= 12:
- i = 0
-
-
- if isstop is True:
- isloop = False
- stopid = i
- break
-
-
- def my_stop():
-
- global isstop
-
-
- if isstop is True:
- return
-
- isstop = True
-
-
- def newtask():
-
- global isloop
- global isstop
-
- isstop = False
-
-
- t = threading.Thread(target=round)
-
- t.start()
-
-
- isloop = True
-
-
- btn_start = tkinter.Button(root, text='開始', command=newtask)
- btn_start.place(x=90, y=125, width=50, height=50)
-
-
- btn_stop = tkinter.Button(root, text='中止', command=my_stop)
- btn_stop.place(x=160, y=125, width=50, height=50)
-
- root.mainloop()

歡迎關注本站公眾號,獲取更多信息