使用 Tkinter 在 Python 中進行顏色遊戲
對於開發 GUI 應用程式來說,tkinter 是一種非常流行且簡單的工具。使用 tkinter 可以輕鬆開發 GUI 遊戲。
這裡我們也嘗試開發一款顏色遊戲。在這個遊戲中,玩家必須輸入螢幕上出現的單詞的顏色,因此得分會增加 1,玩這個遊戲的總時間為 30 秒,在這個遊戲中使用的顏色有紅色、藍色、綠色、粉色、黑色、黃色、橙色、白色、紫色和棕色。介面將以不同的顏色顯示不同顏色的名稱。使用者必須識別顏色並輸入正確的顏色名稱才能贏得遊戲。
示例程式碼
import tkinter import random # list of colour. my_colours = ['Red','Blue','Green','Pink','Black','Yellow','Orange','White','Purple','Brown'] my_score = 0 my_timeleft = 30 def my_startGame(event): if my_timeleft == 30: # start the countdown timer. my_countdown() my_nextColour() def my_nextColour(): global my_score global my_timeleft # if a game is currently in play if my_timeleft > 0: e.focus_set() if e.get().lower() == my_colours[1].lower(): my_score += 1 # clear the text entry box. e.delete(0, tkinter.END) random.shuffle(my_colours) label.config(fg = str(my_colours[1]), text = str(my_colours[0])) # update the score. my_scoreLabel.config(text = "Score: " + str(my_score)) # Countdown timer function def my_countdown(): global my_timeleft # if a game is in play if my_timeleft > 0: # decrement the timer. my_timeleft -= 1 # update the time left label timeLabel.config(text = "Time left: "+ str(my_timeleft)) # run the function again after 1 second. timeLabel.after(1000, my_countdown) # Driver Code root = tkinter.Tk() root.title("COLORGAME") root.geometry("375x200") my_instructions = tkinter.Label(root, text = "Type in the color" "of the words, and not the word text!", font = ('Helvetica', 12)) my_instructions.pack() my_scoreLabel = tkinter.Label(root, text = "Press enter to start", font = ('Helvetica', 12)) my_scoreLabel.pack() my_timeLabel = tkinter.Label(root, text = "Time left: " + str(my_timeleft), font = ('Helvetica', 12)) my_timeLabel.pack() label = tkinter.Label(root, font = ('Helvetica', 60)) label.pack() e = tkinter.Entry(root) root.bind('<Return>', my_startGame) e.pack() e.focus_set() # start the GUI root.mainloop()
輸出


廣告