Python Tkinter教程系列03:随机排列字母猜单词游戏
演练
当用户运行程序时,用户将在Tkinter窗口中看到一个混乱的单词。现在,用户必须从提供的混杂单词中猜测实际单词,然后在输入小部件中输入他们的猜测。现在,要检查猜出的单词是否正确,用户必须按下check
按钮。
如果猜出的单词是正确的,则标签会将其图像转换为Win
,并向用户显示正确的单词。我们的程序还将向我们显示用户猜测正确单词所花费的时间。
如果用户的猜测是错误的,则标签将显示Lose
图像,并且清除输入小部件以再次输入单词。如果用户的猜测是错误的,我们的程序将不会显示正确的单词或时间。
如果用户想再次玩游戏,则等待3秒钟,新窗口将打开并显示新单词。如果用户想终止游戏,则必须按下close
窗口上的按钮。我们的程序还将在各种事件中播放不同的声音文件。
Tkinter中的行列表示
用Python实现(12个步骤)
1.导入所需的库
#Import required libraries from tkinter import * import simpleaudio as sa import random import tkinter.font as font import time
tkinter
:在我们的应用程序中添加小部件simpleaudio
:播放声音文件random
:选择一个随机词tkinter.font
:更改字体的属性time
:计算用户花费的时间
2.创建tkinter主窗口
running = True while running==True: #Calculate starting time start_time = time.time() root = Tk() root.geometry('+100+0') root.configure(bg="#000000") root.iconphoto(True,PhotoImage(file="Surprise.png")) root.title("JUMBLE WORDS") root.resizable(width=False,height=False)
- 首先,我们创建一个名为的变量
running
,并将其值设置为True
。当变量设置为时,我们的程序将生成一个新窗口True
。当用户按下标题栏中的主关闭按钮时,它将退出循环。 root = Tk( )
:用于初始化我们的tkinter模块。root.title( )
:我们使用它来设置应用程序的标题。root.geometry( )
:我们使用它来指定我们的应用程序窗口将在哪个位置打开。在我们的例子中,它将在左上角的左100点和下角的0点处打开。root.configure( )
:我们使用它来指定应用程序的背景色。在我们的情况下,背景颜色为黑色。root.resizable( )
:在这里我们使用它来防止用户调整主窗口的大小。root.iconphoto( )
:我们使用它来设置应用程序窗口标题栏中的图标。我们将第一个参数设置为True
,以确保从该应用程序创建的所有其他窗口具有相同的图标。- 在这里,我们还创建了一个名为的变量
start time
,该变量存储了打开窗口时的时间值。
3.加载声音文件
#Load sound files start = sa.WaveObject.from_wave_file("Start.wav") one = sa.WaveObject.from_wave_file("Win.wav") two = sa.WaveObject.from_wave_file("Lose.wav") three = sa.WaveObject.from_wave_file("6.wav") start.play()
现在,我们将使用一些将在各种事件中播放的声音文件。当我们的程序启动时,它将播放start
文件。当用户的猜测正确,用户的猜测错误以及用户关闭应用程序时,我们将分别播放其他三个文件。
需要注意的一件事是它仅接受.wav
文件。首先,我们需要将声音文件作为对象加载。然后我们可以.play( )
在需要时使用方法播放它。
4.随机选择一个单词
#select a word from list def random_word(): words=["RAIN","CLOUD","NATURE","BEAUTIFUL","HOUSE"] pick = random.choice(words) return pick
此功能将从提供的单词列表中随机选择一个单词。它可以包含任意多个单词。该random.choice( )
方法从单词列表中随机选择一个单词。然后,我们将返回该单词以在其他函数中使用它。
5.杂乱选择的单词
# Jumble the selected word def jumbled_word(word): word = ranom.sample(word,len(word)) word_jumbled = "".join(word) return word_jumbled
既然我们的程序已经选择了一个单词,我们就需要为游戏添加一些单词。该功能输入了我们先前功能选择的单词。该random.sample( )
函数接受一个单词,对其进行混杂,然后给出字母列表。我们可以指定单词的长度,但是在我们的情况下,它将与原始单词相同。然后,我们需要将混杂的字母连接起来以组成一个字符串。最后,它将返回混杂单词,以便我们可以在下一个函数中使用它。
6.安排字母
# Randmoly selected word pick = random_word() # Jumbled word jumbled = jumbled_word(pick) # Get the letters from the jumbled word list1 = list(jumbled) len_list1 = len(list1) # Get the Images for our letters for i in range(len_list1): list1[i] = PhotoImage(file=str(list1[i])+str("_P.png")) row_0 = 0 col_0 = 0 # Arrange the letters on the main window for i in range(len_list1): B = Label(root,image=list1[i]) B.grid(row=row_0,column=col_0) col_0 = col_0 + 1
- 随机选择的单词将存储在
pick
变量中。 - 混乱的单词将存储在
jumbled
变量中。 List1
会将我们的字符串转换为字母列表。len_list1
给了我们单词的长度。- 然后,我们为字母加载图像。我们的图片存储为
A_P.png
,B_P.png
,C_P.png
,等等。 - 我们希望字母图像显示为标签,并且应该在一行上。随着新字母的到来,我们将增加列的值。最终结果将是混乱的单词,表示为图像标签。
7.加载其他所需的图像
# Blank space for row_1 root.gird_rowconfigure(1, minsize=10) # Modify font myFont = font.Font(family='Calibri', weight='bold') # For label image your_choice = PhotoImage(file"YOUR_GUESS.png") surprise = PhotoImage(file="suprprise.png") win = PhotoImage(file="WINNN.png") lose = PhotoImage(file="LOSEEE.png") check = PhotoImage(file="CHECKK.png") close = PhotoImage(file="CLOSEE.png")
- 添加单词后,我们将添加空白行以减少拥塞。
- 现在,我们将修改字体以供以后在条目小部件中使用。
- 现在,我们需要为各种图像
main label
,win
,lose
,check
,close
,等,所以,在这里我们将它们载入变量以后使用它。
8.添加条目小部件
#Entry label label = Label(root,image=your_choice) label.grid(row=2,column=0,columnspan=len_list1) label["font"] = myFont #Add blank space root.grid_rowconfigure(3, minsize=10) #Add entry widget e1 = Entry(root,bd=5,bg="#9ca1db",justify=CENTER,font=myFont,fg="#000000") e1.grid(row=4,column=0,columnspan=len_list1) #Add blank space root.grid_rowconfigure(5, minsize=10)
- 现在,我们将添加一个标签,输入您的猜测。在这里,我们使用在上一点中所做的修改后的字体。
- 之后,我们只是添加空白。
- 现在,我们添加了条目小部件,用户将在其中输入他们的猜词。在这里,我们
columnspan
用来使它成为中心。 - 现在,我们再次添加一个空格。
9.原始文字图片
#Check button button =Button(root,image=check,command=lambda:result()) button.grid(row=6,column=0) #Close button Btn = Button(root,image=close,command=lambda:reset()) Btn.grid(row=6,column=len_list1-1) #Add blank space root.grid_rowconfigure(7, minsize=10)
现在,我们需要添加复选按钮和关闭按钮。按下这些按钮将分别触发result( )
和reset( )
功能。该Check
按钮将在第一列上,而关闭按钮将在最后一列上。
10.结果和时间标签
#Label that will display result label2 = Label(root,image=surprise) label2.grid(row=8,column=0,columnspan=len_list1) root.grid_rowconfigure(9, minsize=10) #Modify the fonts myFont = font.Font(family='Comic Sans MS',weight='bold') #Label to show time taken label3= Label(root,text="TIME : ",width=12,bg="#f5ab55",justify=CENTER,font=myFont,fg="#000000",relief=RAISED) label3.grid(row=12,column=0,columnspan=len_list1)
- 在这里,我们添加了一个标签,该标签将显示结果供用户猜测。
- 我们。也正在再次修改字体以在时间标签中使用。该
time
标签将显示用户猜测正确答案的时间。
11.计算决策的主要功能
#Function to check whether the user's guess is correct or not def result(): #Get the entry value in upper case answer = (e1.get()).upper() if answer == pick: #Caculate the time consumed time_taken = time.time() - start_time time_taken = int(time_taken) #Change the label label3.configure(text="TIME : "+str(time_taken)+" Sec") #Play win sound one.play() #Change label image to win label2.configure(image=win) #Showing original word col_2=0 row_2=10 #Display the origianl word for i in range(len_list1): B = Label(root,image=list2[i]) B.grid(row=row_2,column=col_2) col_2 = col_2+1 #Add blank space root.grid_rowconfigure(11, minsize=10) #To play again after 3 sec root.update_idletasks() root.after(3000) root.destroy() else: #Play a sound file two.play() #Change the label label2.configure(image=lose) #Change back to original label image root.update_idletasks() root.after(500) label2.configure(image=surprise) #Clear the entry e1.delete(0,"end")
- 首先,我们采用用户在输入小部件中输入的值。
- 然后,我们正在检查用户输入的单词是否正确。如果单词正确,它将计算出用户猜单词所花费的时间。然后,将更改时间标签的文本以显示用户花费的时间。
- 之后,它将播放声音文件。标签将在此处显示
WIN
图像。现在,我们将显示实际单词的图像标签。我们的程序将等待3秒钟,关闭当前窗口,然后打开一个新窗口。 - 如果用户输入了错误的单词,标签将显示
lose
图像,并且清除输入小部件以供用户重新输入该单词。0.5秒后,Lose
标签将返回其原始图像。
12. Reset( )
功能进入主循环
def reset(): #Play a sound file : three.play() #Change the running value to false : global running running=False #CLose the main window : root.destroy() #Enter the main loop : root.mainloop()
- 如果用户按下关闭按钮,则该
reset( )
功能将触发。它将运行变量设置为,False
以便我们的程序无法打开新窗口。 - 然后,我们必须进入主循环以运行程序。如果我们的程序没有这一行,它将无法正常工作。
放在一起
查看此Python Tkinter游戏的完整代码。
#Import required libraries : from tkinter import * import simpleaudio as sa import random import tkinter.font as font import time running = True while running==True: #Calculate starting time : start_time = time.time() root = Tk() root.geometry('+100+0') root.configure(bg="#000000") root.iconphoto(True,PhotoImage(file="Surprise.png")) root.title("JUMBLE WORDS") root.resizable(width=False,height=False) #Load sound files : start = sa.WaveObject.from_wave_file("Start.wav") one = sa.WaveObject.from_wave_file("Win.wav") two = sa.WaveObject.from_wave_file("Lose.wav") three = sa.WaveObject.from_wave_file("6.wav") start.play() #Select a word from list : def random_word(): words=["RAIN","CLOUD","NATURE","BEAUTIFUL","HOUSE"] pick = random.choice(words) return pick #Jumble the selected word : def jumbled_word(word): word = random.sample(word,len(word)) word_jumbled = "".join(word) return word_jumbled #Randomly selected word : pick = random_word() #Jumbled word : jumbled = jumbled_word(pick) #Get the letters from jumbled word : list1 = list(jumbled) len_list1 = len(list1) #Get the PhotoImages for our letters : for i in range(len_list1): list1[i] = PhotoImage(file=str(list1[i])+str("_P.png")) row_0 = 0 col_0 = 0 #Arrange the letters on the main window : for i in range(len_list1): B = Label(root,image=list1[i]) B.grid(row=row_0,column=col_0) col_0 = col_0 + 1 #Blank space for row_1 : root.grid_rowconfigure(1, minsize=10) #Modify font : myFont = font.Font(family='Calibri', weight='bold') #For label image : your_choice = PhotoImage(file="YOUR_GUESS.png") surprise = PhotoImage(file="surprise.png") win = PhotoImage(file="WINNN.png") lose = PhotoImage(file="LOSEEE.png") check = PhotoImage(file="CHECKK.png") close = PhotoImage(file="CLOSEE.png") #To arrange the labels in center : #x = math.floor(len_list1/2) #Entry label : label = Label(root,image=your_choice) label.grid(row=2,column=0,columnspan=len_list1) label["font"] = myFont #Add blank space : root.grid_rowconfigure(3, minsize=10) #Add entry widget : e1 = Entry(root,bd=5,bg="#9ca1db",justify=CENTER,font=myFont,fg="#000000") e1.grid(row=4,column=0,columnspan=len_list1) #Add blank space : root.grid_rowconfigure(5, minsize=10) #Get the entry value in upper case : answer = (e1.get()).upper() #Make list of correct word : list2=list(pick) #Load images for correct word : for j in range(len(list2)): list2[j] = PhotoImage(file=str(list2[j])+str("_P.png")) #Check button : button =Button(root,image=check,command=lambda:result()) button.grid(row=6,column=0) #Close button : Btn = Button(root,image=close,command=lambda:reset()) Btn.grid(row=6,column=len_list1-1) #Add blank space : root.grid_rowconfigure(7, minsize=10) #Label that will display result : label2 = Label(root,image=surprise) label2.grid(row=8,column=0,columnspan=len_list1) root.grid_rowconfigure(9, minsize=10) #Modify the fonts : myFont = font.Font(family='Comic Sans MS',weight='bold') #Label to show time taken : label3= Label(root,text="TIME : ",width=12,bg="#f5ab55",justify=CENTER,font=myFont,fg="#000000",relief=RAISED) label3.grid(row=12,column=0,columnspan=len_list1) #Function to check whether the user's guess is correct or not : def result(): #Get the entry value in upper case : answer = (e1.get()).upper() if answer == pick: #Caculate the time consumed : time_taken = time.time() - start_time time_taken = int(time_taken) #Change the label : label3.configure(text="TIME : "+str(time_taken)+" Sec") #Play win sound : one.play() #Change label image to win : label2.configure(image=win) #Showing original word : col_2=0 row_2=10 #Display the origianl word : for i in range(len_list1): B = Label(root,image=list2[i]) B.grid(row=row_2,column=col_2) col_2 = col_2+1 #Add blank space : root.grid_rowconfigure(11, minsize=10) #To play again after 3 sec : root.update_idletasks() root.after(3000) root.destroy() else: #Play a sound file : two.play() #Change the label : label2.configure(image=lose) #Change back to original label image : root.update_idletasks() root.after(500) label2.configure(image=surprise) #Clear the entry : e1.delete(0,"end") #Function that triggers by pressing CLOSE button : def reset(): #Play a sound file : three.play() #Change the running value to false : global running running=False #CLose the main window : root.destroy() #Enter the main loop : root.mainloop()
1. 本站资源转自互联网,源码资源分享仅供交流学习,下载后切勿用于商业用途,否则开发者追究责任与本站无关!
2. 本站使用「署名 4.0 国际」创作协议,可自由转载、引用,但需署名原版权作者且注明文章出处
3. 未登录无法下载,登录使用金币下载所有资源。
IT小站 » Python Tkinter教程系列03:随机排列字母猜单词游戏
常见问题FAQ
- 没有金币/金币不足 怎么办?
- 本站已开通每日签到送金币,每日签到赠送五枚金币,金币可累积。
- 所有资源普通会员都能下载吗?
- 本站所有资源普通会员都可以下载,需要消耗金币下载的白金会员资源,通过每日签到,即可获取免费金币,金币可累积使用。