Python Tkinter库的简单使用

今天写了两个小小的图像界面小游戏,对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()            

这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值