Python
 Computer >> コンピューター >  >> プログラミング >> Python

PythonでTkinterを使用したカラーゲーム


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()

出力

<中央> PythonでTkinterを使用したカラーゲーム <中央> PythonでTkinterを使用したカラーゲーム
  1. PythonTkinterを使用した簡単な登録フォーム

    Tkinterは、GUI(グラフィカルユーザーインターフェイス)を開発するためのPythonライブラリです。 tkinterライブラリを使用してUI(ユーザーインターフェイス)のアプリケーションを作成し、ウィンドウやその他すべてのグラフィカルユーザーインターフェイスを作成します。 python 3.x(推奨)を使用している場合、TkinterにはPythonが標準パッケージとして付属しているため、使用するために何もインストールする必要はありません。 Tkinterで登録フォームを作成する前に、まずTkinterで簡単なGUIアプリケーションを作成しましょう。 簡単なGUIアプリケーションの

  2. PythonでのCX_Freezeの使用

    時々私たちは非常にエキサイティングな何か違うものを作りたいと感じます、そして人間の性質によれば、私たちはいつもそれを共有するのが大好きです。 Pythonもそれらの願いを満たします。 Pythonを使用して、Pythonプログラムを友人と共有したい場合は、それを行うことができます。必要なのは、マシンのプログラムで使用されるすべてのモジュールに同じバージョンのPythonをインストールすることだけです。 まず、 pip install CX_Frezzeを使用してCX_Freezeモジュールをインストールする必要があります コマンドプロンプトのコマンド。 最初のステップは、この割り当て、