首页 > Python资料 博客日记
分享10个很酷、简单且有趣的 Python 项目及其源代码
2024-09-15 12:00:05Python资料围观54次
无论我们当前的技能水平如何,学习构建 Python 项目都是提高个人技能和增强作品集的必由之路。没有什么比亲自动手进行一些实际编码和构建 Python 项目更好的了!在本文中,我们收录了 10 个有趣的 Python 项目,从适合初学者的简单 Python 项目到中级和高级 Python 项目,我们可以利用它们来挑战自己或提高 Python 编程技能。
适合初学者的 Python 项目
让我们开始为初学者提供一系列项目,如果您刚刚开始并且想要学习 Python,那么这是理想的选择。换言之,如果您渴望从事更具挑战性的事情,请阅读本文后面内容以查看更高级的项目。
1.Dice Roll Generator
Dice Roll Generator(本文译为掷骰子生成器)作为与代码初学者最相关的 Python 项目之一,该程序模拟掷一两个骰子。这也是巩固对用户定义函数、循环和条件语句的理解的好方法。这些是 Python 初学者的基本技能,并且可能是您首先要学习的一些东西,无论是从在线课程还是Python 书籍中。
作为简单的 Python 项目之一,它是一个相当简单的程序,使用 Python random 模块来复制掷骰子的随机性质。您可能还会注意到,在掷骰子后,使用 os 模块来清除屏幕。请注意,可以将最大骰子值更改为任意数字,从而允许模拟许多棋盘游戏和角色扮演游戏中常用的多面体骰子。
源代码:
'''
Dice Roll Generator
-------------------------------------------------------------
'''
import random
import os
def num_die():
while True:
try:
num_dice = input('Number of dice: ')
valid_responses = ['1', 'one', 'two', '2']
if num_dice not in valid_responses:
raise ValueError('1 or 2 only')
else:
return num_dice
except ValueError as err:
print(err)
def roll_dice():
min_val = 1
max_val = 6
roll_again = 'y'
while roll_again.lower() == 'yes' or roll_again.lower() == 'y':
os.system('cls' if os.name == 'nt' else 'clear')
amount = num_die()
if amount == '2' or amount == 'two':
print('Rolling the dice...')
dice_1 = random.randint(min_val, max_val)
dice_2 = random.randint(min_val, max_val)
print('The values are:')
print('Dice One: ', dice_1)
print('Dice Two: ', dice_2)
print('Total: ', dice_1 + dice_2)
roll_again = input('Roll Again? ')
else:
print('Rolling the die...')
dice_1 = random.randint(min_val, max_val)
print(f'The value is: {dice_1}')
roll_again = input('Roll Again? ')
if __name__ == '__main__':
roll_dice()
2.Hangman Game
这是一个有趣的 Python 项目想法,用于模拟猜词游戏 Hangman。在猜测方面使用了预定义的单词列表,但可以随意使用第三方词典 API 来改进这一点。
此 Python 项目使用循环、函数和字符串格式来打印 Hangman 的进度。它还允许试验标准库的 random、time 和 os 模块。具体来说,使用 random 模块来选择要猜测的单词,并使用 os 模块来清除屏幕,以及使用 time 模块的 .sleep() 函数来引入暂停以增强游戏流程。
如果您目前正在学习 Python 课程并且对这门语言仍然陌生,那么这是一个很好的中型项目,可以让您自我拓展!
源代码:
'''
Hangman Game
-------------------------------------------------------------
'''
import random
import time
import os
def play_again():
question = 'Do You want to play again? y = yes, n = no \n'
play_game = input(question)
while play_game.lower() not in ['y', 'n']:
play_game = input(question)
if play_game.lower() == 'y':
return True
else:
return False
def hangman(word):
display = '_' * len(word)
count = 0
limit = 5
letters = list(word)
guessed = []
while count < limit:
guess = input(f'Hangman Word: {display} Enter your guess: \n').strip()
while len(guess) == 0 or len(guess) > 1:
print('Invalid input. Enter a single letter\n')
guess = input(
f'Hangman Word: {display} Enter your guess: \n').strip()
if guess in guessed:
print('Oops! You already tried that guess, try again!\n')
continue
if guess in letters:
letters.remove(guess)
index = word.find(guess)
display = display[:index] + guess + display[index + 1:]
else:
guessed.append(guess)
count += 1
if count == 1:
time.sleep(1)
print(' _____ \n'
' | \n'
' | \n'
' | \n'
' | \n'
' | \n'
' | \n'
'__|__\n')
print(f'Wrong guess: {limit - count} guesses remaining\n')
elif count == 2:
time.sleep(1)
print(' _____ \n'
' | | \n'
' | | \n'
' | \n'
' | \n'
' | \n'
' | \n'
'__|__\n')
print(f'Wrong guess: {limit - count} guesses remaining\n')
elif count == 3:
time.sleep(1)
print(' _____ \n'
' | | \n'
' | | \n'
' | | \n'
' | \n'
' | \n'
' | \n'
'__|__\n')
print(f'Wrong guess: {limit - count} guesses remaining\n')
elif count == 4:
time.sleep(1)
print(' _____ \n'
' | | \n'
' | | \n'
' | | \n'
' | O \n'
' | \n'
' | \n'
'__|__\n')
print(f'Wrong guess: {limit - count} guesses remaining\n')
elif count == 5:
time.sleep(1)
print(' _____ \n'
' | | \n'
' | | \n'
' | | \n'
' | O \n'
' | /|\ \n'
' | / \ \n'
'__|__\n')
print('Wrong guess. You\'ve been hanged!!!\n')
print(f'The word was: {word}')
if display == word:
print(f'Congrats! You have guessed the word \'{word}\' correctly!')
break
def play_hangman():
print('\nWelcome to Hangman\n')
name = input('Enter your name: ')
print(f'Hello {name}! Best of Luck!')
time.sleep(1)
print('The game is about to start!\nLet\'s play Hangman!')
time.sleep(1)
os.system('cls' if os.name == 'nt' else 'clear')
words_to_guess = [
'january', 'border', 'image', 'film', 'promise', 'kids',
'lungs', 'doll', 'rhyme', 'damage', 'plants', 'hello', 'world'
]
play = True
while play:
word = random.choice(words_to_guess)
hangman(word)
play = play_again()
print('Thanks For Playing! We expect you back again!')
exit()
if __name__ == '__main__':
play_hangman()
3.Countdown Clock and Timer
Countdown Clock and Timer(倒计时和计时器)这个 Python 项目的想法很有趣!在这里,我们创建了一个倒计时器,它通过用户输入要求用户输入几秒,然后一秒一秒地倒计时,直到显示一条消息。
使用 Python 时间模块的 .sleep()
函数来暂停 1 秒的时间间隔,我们将其与一些实用的字符串格式结合起来以生成倒计时显示。
源代码:
'''
Countdown Timer
-------------------------------------------------------------
'''
import time
def countdown(user_time):
while user_time >= 0:
mins, secs = divmod(user_time, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end='\r')
time.sleep(1)
user_time -= 1
print('Lift off!')
if __name__ == '__main__':
user_time = int(input("Enter a time in seconds: "))
countdown(user_time)
带有源代码的中级 Python 项目
4.Currency Converter
Currency Converter(货币转换器)是要求安装的 Python 库中最流行的 Python 项目想法之一,在本例中是 requests 模块。它不包含在 Python 标准库中,因此请使用源代码中显示的 pip 命令将其安装到系统上。
通过 requests 模块,可以向 Fixer API 发出 HTTP 请求,从而将一种货币转换为另一种,可能会注意到我们正在使用第 3 方 API,因此需要注册才能获取免费的 API 密钥。然后可在源代码中显示的字段中输入 API 密钥,之后就可以开始了!
该项目允许获得更多有关循环和用户输入的练习,但它通过 HTTP 请求对此进行了扩展,以检索 JSON 格式的 API 数据。如果不熟悉 JSON,它与 Python 字典非常相似,这意味着可以访问键值对来获取我们想要的数据。在本例中正在查找 API 调用的货币换算结果。有关可检索的不同数据的更多详细信息。
源代码:
'''
Currency Converter
-------------------------------------------------------------
pip install requests
'''
import requests
def convert_currency():
init_currency = input('Enter an initial currency: ')
target_currency = input('Enter a target currency: ')
while True:
try:
amount = float(input('Enter the amount: '))
except:
print('The amount must be a numeric value!')
continue
if not amount > 0:
print('The amount must be greater than 0')
continue
else:
break
url = ('https://api.apilayer.com/fixer/convert?to='
+ target_currency + '&from=' + init_currency +
'&amount=' + str(amount))
payload = {}
headers = {'apikey': 'YOUR API KEY'}
response = requests.request('GET', url, headers=headers, data=payload)
status_code = response.status_code
if status_code != 200:
print('Uh oh, there was a problem. Please try again later')
quit()
result = response.json()
print('Conversion result: ' + str(result['result']))
if __name__ == '__main__':
convert_currency()
5.Pascal’s Triangle
这个 Python 项目使用条件语句和循环打印出 Pascal 三角形。它还使用标准库的数学模块和阶乘函数来评估用于生成三角形中值的“组合数”方程。对三角形的种子数进行实验,以检查如何使用“组合”方程在三角形中生成连续值。
源代码:
'''
Pascal's Triangle
-------------------------------------------------------------
Number of combinations via "n choose k" or nCk = n! / [k! * (n-k)!]
'''
from math import factorial
def pascal_triangle(n):
for i in range(n):
for j in range(n-i+1):
print(end=' ')
for j in range(i+1):
print(factorial(i)//(factorial(j)*factorial(i-j)), end=' ')
print()
if __name__ == '__main__':
pascal_triangle(5)
6.Blackjack
Blackjack 作为最酷的 Python 项目之一,这将吸引任何喜欢纸牌游戏的人,因为我们将模拟 Blackjack。这是一款超级流行的纸牌游戏,规则相对简单:最重要的是你需要 21 才能获胜,或者需要比庄家更高的分数而不至于破产!
这是迄今为止清单上最大的项目。它结合了在以前的项目中已经介绍过的大部分技能,包括创建类、循环、条件语句、导入模块、接受用户输入和字符串格式化。
花点时间研究此代码的不同部分,并将其与早期的项目联系起来,以了解不同的技术如何协同工作。没有什么是你没见过的;它只是打包方式略有不同,并组合起来创建一个功能齐全的游戏模拟器。
源代码:
'''
Blackjack
-------------------------------------------------------------
'''
import random
import os
class Card:
def __init__(self, card_face, value, symbol):
self.card_face = card_face
self.value = value
self.symbol = symbol
def show_cards(cards, hidden):
s = ''
for card in cards:
s = s + '\t ________________'
if hidden:
s += '\t ________________'
print(s)
s = ''
for card in cards:
s = s + '\t| |'
if hidden:
s += '\t| |'
print(s)
s = ''
for card in cards:
if card.card_face in ['J', 'Q', 'K', 'A']:
s = s + '\t| {} |'.format(card.card_face)
elif card.value == 10:
s = s + '\t| {} |'.format(card.value)
else:
s = s + '\t| {} |'.format(card.value)
if hidden:
s += '\t| |'
print(s)
s = ''
for card in cards:
s = s + '\t| |'
if hidden:
s += '\t| * * |'
print(s)
s = ''
for card in cards:
s = s + '\t| |'
if hidden:
s += '\t| * * |'
print(s)
s = ''
for card in cards:
s = s + '\t| |'
if hidden:
s += '\t| * * |'
print(s)
s = ''
for card in cards:
s = s + '\t| |'
if hidden:
s += '\t| * * |'
print(s)
s = ''
for card in cards:
s = s + '\t| {} |'.format(card.symbol)
if hidden:
s += '\t| * |'
print(s)
s = ''
for card in cards:
s = s + '\t| |'
if hidden:
s += '\t| * |'
print(s)
s = ''
for card in cards:
s = s + '\t| |'
if hidden:
s += '\t| * |'
print(s)
s = ''
for card in cards:
s = s + '\t| |'
if hidden:
s += '\t| |'
print(s)
s = ''
for card in cards:
s = s + '\t| |'
if hidden:
s += '\t| |'
print(s)
s = ''
for card in cards:
if card.card_face in ['J', 'Q', 'K', 'A']:
s = s + '\t| {} |'.format(card.card_face)
elif card.value == 10:
s = s + '\t| {} |'.format(card.value)
else:
s = s + '\t| {} |'.format(card.value)
if hidden:
s += '\t| * |'
print(s)
s = ''
for card in cards:
s = s + '\t|________________|'
if hidden:
s += '\t|________________|'
print(s)
print()
def deal_card(deck):
card = random.choice(deck)
deck.remove(card)
return card, deck
def play_blackjack(deck):
player_cards = []
dealer_cards = []
player_score = 0
dealer_score = 0
os.system('clear')
while len(player_cards) < 2:
player_card, deck = deal_card(deck)
player_cards.append(player_card)
player_score += player_card.value
# If dealt a second Ace, adjust player score
if len(player_cards) == 2:
if player_cards[0].value == 11 and player_cards[1].value == 11:
player_cards[0].value = 1
player_score -= 10
print('PLAYER CARDS: ')
show_cards(player_cards, False)
print('PLAYER SCORE = ', player_score)
input('Continue...')
dealer_card, deck = deal_card(deck)
dealer_cards.append(dealer_card)
dealer_score += dealer_card.value
# If dealt a second Ace, adjust dealer score
# Note: adjusts 2nd card to hide that the dealer has an Ace
if len(dealer_cards) == 2:
if dealer_cards[0].value == 11 and dealer_cards[1].value == 11:
dealer_cards[1].value = 1
dealer_score -= 10
print('DEALER CARDS: ')
if len(dealer_cards) == 1:
show_cards(dealer_cards, False)
print('DEALER SCORE = ', dealer_score)
else:
show_cards(dealer_cards[:-1], True)
print('DEALER SCORE = ', dealer_score - dealer_cards[-1].value)
input('Continue...')
if player_score == 21:
print('PLAYER HAS A BLACKJACK!!!!')
print('PLAYER WINS!!!!')
quit()
os.system('clear')
print('DEALER CARDS: ')
show_cards(dealer_cards[:-1], True)
print('DEALER SCORE = ', dealer_score - dealer_cards[-1].value)
print()
print('PLAYER CARDS: ')
show_cards(player_cards, False)
print('PLAYER SCORE = ', player_score)
while player_score < 21:
choice = input('Enter H to Hit or S to Stand: ').upper()
if len(choice) != 1 or (choice not in ['H', 'S']):
os.system('clear')
print('Invalid choice!! Try Again...')
continue
if choice.upper() == 'S':
break
else:
player_card, deck = deal_card(deck)
player_cards.append(player_card)
player_score += player_card.value
card_pos = 0
# If dealt an Ace, adjust score for each existing Ace in hand
while player_score > 21 and card_pos < len(player_cards):
if player_cards[card_pos].value == 11:
player_cards[card_pos].value = 1
player_score -= 10
card_pos += 1
else:
card_pos += 1
if player_score > 21:
break
os.system('clear')
print('DEALER CARDS: ')
show_cards(dealer_cards[:-1], True)
print('DEALER SCORE = ', dealer_score - dealer_cards[-1].value)
print()
print('PLAYER CARDS: ')
show_cards(player_cards, False)
print('PLAYER SCORE = ', player_score)
os.system('clear')
print('PLAYER CARDS: ')
show_cards(player_cards, False)
print('PLAYER SCORE = ', player_score)
print()
print('DEALER IS REVEALING THEIR CARDS....')
print('DEALER CARDS: ')
show_cards(dealer_cards, False)
print('DEALER SCORE = ', dealer_score)
if player_score == 21:
print('PLAYER HAS A BLACKJACK, PLAYER WINS!!!')
quit()
if player_score > 21:
print('PLAYER BUSTED!!! GAME OVER!!!')
quit()
input('Continue...')
while dealer_score < 17:
os.system('clear')
print('DEALER DECIDES TO HIT.....')
dealer_card, deck = deal_card(deck)
dealer_cards.append(dealer_card)
dealer_score += dealer_card.value
# If dealt an Ace, adjust score for each existing Ace in hand
card_pos = 0
while dealer_score > 21 and card_pos < len(dealer_cards):
if dealer_cards[card_pos].value == 11:
dealer_cards[card_pos].value = 1
dealer_score -= 10
card_pos += 1
else:
card_pos += 1
print('PLAYER CARDS: ')
show_cards(player_cards, False)
print('PLAYER SCORE = ', player_score)
print()
print('DEALER CARDS: ')
show_cards(dealer_cards, False)
print('DEALER SCORE = ', dealer_score)
if dealer_score > 21:
break
input('Continue...')
if dealer_score > 21:
print('DEALER BUSTED!!! YOU WIN!!!')
quit()
elif dealer_score == 21:
print('DEALER HAS A BLACKJACK!!! PLAYER LOSES!!!')
quit()
elif dealer_score == player_score:
print('TIE GAME!!!!')
elif player_score > dealer_score:
print('PLAYER WINS!!!')
else:
print('DEALER WINS!!!')
def init_deck():
suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds']
# UNICODE values for card symbol images
suit_symbols = {'Hearts': '\u2661', 'Diamonds': '\u2662',
'Spades': '\u2664', 'Clubs': '\u2667'}
cards = {'A': 11, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6,
'7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}
deck = []
for suit in suits:
for card, value in cards.items():
deck.append(Card(card, value, suit_symbols[suit]))
return deck
if __name__ == '__main__':
deck = init_deck()
play_blackjack(deck)
高级 Python 项目
7.Text to Speech(文字转语音)
此 Python 项目使用一系列新库将现有文章转换为可播放的 mp3 文件。需要安装 nltk(自然语言工具包)、newspaper3k 和 gtts。
您会发现该程序很简单,我们只需传入要转换的文章的 URL,然后让定义的函数使用新安装的模块处理文本到语音的转换。因此,下次当您想将文章变成可播放的播客时,请考虑尝试一下,它绝对是值得复制的很酷的 Python 代码之一!
源代码:
'''
Text To Speech
-------------------------------------------------------------
pip install nltk newspaper3k gtts
'''
import nltk
from newspaper import Article
from gtts import gTTS
def text_to_speech(url):
article = Article(url)
article.download()
article.parse()
nltk.download('punkt')
article.nlp()
article_text = article.text
language = 'en'
my_obj = gTTS(text=article_text, lang=language, slow=False)
my_obj.save("read_article.mp3")
if __name__ == '__main__':
text_to_speech(
url='https://hackr.io/blog/top-tech-companies-hiring-python-developers'
)
8.Pong Arcade Game
Pong Arcade Game 是一个非常有趣的项目,因为我们使用 Python turtle 模块来模拟经典街机游戏 Pong!
我们使用了 turtle 模块中的各种方法来创建游戏组件,并检测球与玩家球拍的碰撞。我们还定义了一系列键绑定,以设置左右玩家划桨的用户控件。请随意尝试游戏的设置,以更好地了解每个设置是如何工作和影响整个游戏。
除了这些新引入的 turtle 图形函数之外,还使用字符串格式来输出当前记分板和用户定义的函数,以保持代码整洁,这些是现阶段应该熟悉的概念。
源代码:
'''
Pong Arcade Game
-------------------------------------------------------------
'''
import turtle
def update_score(l_score, r_score, player, score_board):
if player == 'l':
l_score += 1
else:
r_score += 1
score_board.clear()
score_board.write('Left Player: {} -- Right Player: {}'.format(
l_score, r_score), align='center',
font=('Arial', 24, 'normal'))
return l_score, r_score, score_board
def setup_game():
screen = turtle.Screen()
screen.title('Pong Arcade Game')
screen.bgcolor('white')
screen.setup(width=1000, height=600)
l_paddle = turtle.Turtle()
l_paddle.speed(0)
l_paddle.shape('square')
l_paddle.color('red')
l_paddle.shapesize(stretch_wid=6, stretch_len=2)
l_paddle.penup()
l_paddle.goto(-400, 0)
r_paddle = turtle.Turtle()
r_paddle.speed(0)
r_paddle.shape('square')
r_paddle.color('black')
r_paddle.shapesize(stretch_wid=6, stretch_len=2)
r_paddle.penup()
r_paddle.goto(400, 0)
ball = turtle.Turtle()
ball.speed(40)
ball.shape('circle')
ball.color('blue')
ball.penup()
ball.goto(0, 0)
ball.dx = 5
ball.dy = -5
score_board = turtle.Turtle()
score_board.speed(0)
score_board.color('blue')
score_board.penup()
score_board.hideturtle()
score_board.goto(0, 260)
score_board.write('Left Player: 0 -- Right Player: 0',
align='center', font=('Arial', 24, 'normal'))
return screen, ball, l_paddle, r_paddle, score_board
def pong_game():
game_components = setup_game()
screen = game_components[0]
ball = game_components[1]
l_paddle = game_components[2]
r_paddle = game_components[3]
score_board = game_components[4]
l_score = 0
r_score = 0
def l_paddle_up():
l_paddle.sety(l_paddle.ycor() + 20)
def l_paddle_down():
l_paddle.sety(l_paddle.ycor() - 20)
def r_paddle_up():
r_paddle.sety(r_paddle.ycor() + 20)
def r_paddle_down():
r_paddle.sety(r_paddle.ycor() - 20)
screen.listen()
screen.onkeypress(l_paddle_up, 'e')
screen.onkeypress(l_paddle_down, 'x')
screen.onkeypress(r_paddle_up, 'Up')
screen.onkeypress(r_paddle_down, 'Down')
while True:
screen.update()
ball.setx(ball.xcor()+ball.dx)
ball.sety(ball.ycor()+ball.dy)
if ball.ycor() > 280:
ball.sety(280)
ball.dy *= -1
if ball.ycor() < -280:
ball.sety(-280)
ball.dy *= -1
if ball.xcor() > 500:
ball.goto(0, 0)
ball.dy *= -1
l_score, r_score, score_board = update_score(
l_score, r_score, 'l', score_board)
continue
elif ball.xcor() < -500:
ball.goto(0, 0)
ball.dy *= -1
l_score, r_score, score_board = update_score(
l_score, r_score, 'r', score_board)
continue
if ((ball.xcor() > 360) and
(ball.xcor() < 370) and
(ball.ycor() < r_paddle.ycor()+40) and
(ball.ycor() > r_paddle.ycor()-40)):
ball.setx(360)
ball.dx *= -1
if ((ball.xcor() < -360) and
(ball.xcor() > -370) and
(ball.ycor() < l_paddle.ycor()+40) and
(ball.ycor() > l_paddle.ycor()-40)):
ball.setx(-360)
ball.dx *= -1
if __name__ == '__main__':
pong_game()
9.Text Editor(文本编辑器)
这个有趣的 Python 项目以最后一个 tkinter 示例为基础,创建了一个 GUI 来模拟自己的文本编辑器。此示例还使用标准 GUI 组件,包括标签、按钮和输入字段。
不过还添加了像真正的文本编辑器一样打开和保存文件的功能。如果不熟悉文件处理,那么这个 Python 项目是了解如何读入和保存文件的好方法。
尝试使用下面的代码来巩固您的理解,并看看是否可以扩展此代码以创建您习惯于在文本编辑器中使用的其他功能,例如“查找单词”功能。
源代码:
'''
Text Editor
-------------------------------------------------------------
'''
import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
def text_editor():
def open_file():
filepath = askopenfilename(
filetypes=[('Text Files', '*.txt'), ('All Files', '*.*')]
)
if not filepath:
return
txt_edit.delete(1.0, tk.END)
with open(filepath, 'r') as input_file:
text = input_file.read()
txt_edit.insert(tk.END, text)
window.title(f'TextEditor - {filepath}')
def save_file():
filepath = asksaveasfilename(
defaultextension='txt',
filetypes=[('Text Files', '*.txt'), ('All Files', '*.*')],
)
if not filepath:
return
with open(filepath, 'w') as output_file:
text = txt_edit.get(1.0, tk.END)
output_file.write(text)
window.title(f'Text Editor - {filepath}')
window = tk.Tk()
window.title('Text Editor')
window.rowconfigure(0, minsize=800, weight=1)
window.columnconfigure(1, minsize=800, weight=1)
txt_edit = tk.Text(window)
fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)
btn_open = tk.Button(fr_buttons, text='Open', command=open_file)
btn_save = tk.Button(fr_buttons, text='Save As...', command=save_file)
btn_open.grid(row=0, column=0, sticky='ew', padx=5, pady=5)
btn_save.grid(row=1, column=0, sticky='ew', padx=5)
fr_buttons.grid(row=0, column=0, sticky='ns')
txt_edit.grid(row=0, column=1, sticky='nsew')
window.mainloop()
if __name__ == '__main__':
text_editor()
10.Speed Typing Test(快速打字测试)
Speed Typing Test 是一个有趣的 Python 项目,它测试你能多快准确地打出一个句子。
该程序要求我们通过 tkinter 模块创建图形用户界面(GUI)。如果您是 GUI 新手,这个示例是一个很好的介绍,我们使用一系列简单的标签、按钮和输入字段来创建窗口,还使用 Python timeit 模块来处理打字测试的计时方面,并使用 random 模块来随机选择测试短语。
仅在此示例中添加了两个测试短语,但可以随意尝试更多甚至集成第三方词典以获得更广泛的示例。
源代码:
'''
Speed Typing Test
-------------------------------------------------------------
'''
import tkinter
from timeit import default_timer as timer
import random
def speed_test():
speed_test_sentences = [
'This is a random sentence to check speed.',
'Speed, I am lightning mcqueen.'
]
sentence = random.choice(speed_test_sentences)
start = timer()
main_window = tkinter.Tk()
main_window.geometry('600x400')
label_1 = tkinter.Label(main_window, text=sentence, font='times 20')
label_1.place(x=150, y=10)
label_2 = tkinter.Label(main_window, text='Start Typing', font='times 20')
label_2.place(x=10, y=50)
entry = tkinter.Entry(main_window)
entry.place(x=280, y=55)
def check_result():
if entry.get() == sentence:
end = timer()
label_3.configure(text=f'Time: {round((end-start), 4)}s')
else:
label_3.configure(text='Wrong Input')
button_1 = tkinter.Button(main_window, text='Done',
command=check_result, width=12, bg='grey')
button_1.place(x=150, y=100)
button_2 = tkinter.Button(main_window, text='Try Again',
command=speed_test, width=12, bg='grey')
button_2.place(x=250, y=100)
label_3 = tkinter.Label(main_window, text='', font='times 20')
label_3.place(x=10, y=300)
main_window.mainloop()
if __name__ == '__main__':
speed_test()
需要100个实战项目资源请关注+留言获取
标签:
相关文章
最新发布
- 【Python】selenium安装+Microsoft Edge驱动器下载配置流程
- Python 中自动打开网页并点击[自动化脚本],Selenium
- Anaconda基础使用
- 【Python】成功解决 TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’
- manim边学边做--三维的点和线
- CPython是最常用的Python解释器之一,也是Python官方实现。它是用C语言编写的,旨在提供一个高效且易于使用的Python解释器。
- Anaconda安装配置Jupyter(2024最新版)
- Python中读取Excel最快的几种方法!
- Python某城市美食商家爬虫数据可视化分析和推荐查询系统毕业设计论文开题报告
- 如何使用 Python 批量检测和转换 JSONL 文件编码为 UTF-8
点击排行
- 版本匹配指南:Numpy版本和Python版本的对应关系
- 版本匹配指南:PyTorch版本、torchvision 版本和Python版本的对应关系
- Python 可视化 web 神器:streamlit、Gradio、dash、nicegui;低代码 Python Web 框架:PyWebIO
- 相关性分析——Pearson相关系数+热力图(附data和Python完整代码)
- Python与PyTorch的版本对应
- Anaconda版本和Python版本对应关系(持续更新...)
- Python pyinstaller打包exe最完整教程
- Could not build wheels for llama-cpp-python, which is required to install pyproject.toml-based proj