今天写了两个小小的图像界面小游戏,对Tkinter库进行了简单的熟悉。
1.随机造句小游戏:
import Tkinter as tk
import random
window = tk.Tk()
def randomNoun():
nouns = ["cats", "hippos", "cakes"]
noun = random.choice(nouns)
return noun
def randomVerb():
verbs = ["eats", "likes", "hates", "has"]
verb = random.choice(verbs)
return verb
def buttonClick():
name = nameEntry.get()
verb = randomVerb()
noun = randomNoun()
sentence = name + " " + verb + " " + noun
result.delete(0, tk.END)
result.insert(0, sentence)
nameLabel = tk.Label(window, text="Name:")
nameEntry = tk.Entry(window)
button = tk.Button(window, text="Generate", command=buttonClick)
result = tk.Entry(window)
nameLabel.pack()
nameEntry.pack()
button.pack()
result.pack()
window.mainloop()
一个输入密码的小示例:
import Tkinter as tk
window = tk.Tk()
def checkPassword():
password = "123456"
enteredPassword = passwordEntry.get()
if password == enteredPassword:
confirmLabel.config(text="Correct")
else:
confirmLabel.config(text="Incorrect")
passwordLabel = tk.Label(window, text="Password: ")
passwordEntry = tk.Entry(window, show="*")
button = tk.Button(window, text="Enter", command=checkPassword)
confirmLabel = tk.Label(window)
passwordLabel.pack()
passwordEntry.pack()
button.pack()
confirmLabel.pack()
window.mainloop()
2.一个简单的猜数字游戏,对Python的try:… except:函数的了解。同时认识了Python定义函数的精髓。。。就是空格
import random
import Tkinter as tk
window = tk.Tk()
maxNo = 10
score = 0
rounds = 0
def buttonClick():
global score
global rounds
try:
guess = int(guessBox.get())
if 0 < guess <= maxNo:
result = random.randrange(1, maxNo + 1)
if guess == result:
score = score + 1
rounds = rounds + 1
else:
result = "Entry not valid"
except:
result = "Entry not valid"
resultLabel.config(text=result)
scoreLabel.config(text=str(score)+"/"+str(rounds))
guessBox.delete(0, tk.END)
guessLabel = tk.Label(window, text="Enter a number from 1 to" + str(maxNo))
guessBox = tk.Entry(window)
resultLabel = tk.Label(window)
scoreLabel = tk.Label(window)
button = tk.Button(window, text="guess", command=buttonClick)
guessLabel.pack()
guessBox.pack()
resultLabel.pack()
scoreLabel.pack()
button.pack()
window.mainloop()