Tkinter是Python的Tk GUI(图形用户界面)工具包和事实上的规范GUI 的标准接口。GUI使您能够应用大多数操作系统应用的可视项(例如窗口,图标和菜单)与计算机进行交互。这个功能强大的工具可用于构建各种我的项目,并且使可视化代码更加容易。
在本文中,咱们将理解Tkinter的基础知识以及可在Python应用程序中应用的不同类型的小部件。在本文的前面,咱们将应用Tkinter小部件开发一个很酷的数字猜想游戏。
明天,咱们将介绍:
- Tkinter的根底
- Tkinter的小部件与示例
- 从头开始构建数字猜谜游戏
Tkinter的根底
在构建游戏之前,咱们须要理解Tkinter的一些基础知识。Tkinter软件包是Tk GUI工具包的规范python接口。咱们通常应用Tkinter包在应用程序中插入不同的GUI小部件,以使其更加用户敌对。如果您在Linux,Windows或Mac上应用Python,则设施上曾经装置了Python Tkinter。
咱们如何开发GUI应用程序?
创立GUI应用程序的根本过程如下:
Import the Tkinter ModuleCreate Main WindowAdd WidgetsEnter Main Loop
应用Python开发GUI应用程序波及的步骤:
- 导入tkinter模块。
- 为咱们的GUI应用程序创立主窗口。
- 当初,为咱们的应用程序增加任意数量的小部件。
- 进入主事件循环以执行咱们的次要性能。
当初让咱们看看如何创立一个简略的tkinter窗口:
首先,咱们将导入tkinter模块。它蕴含构建应用程序所需的所有性能,类和其余内容。当初,当咱们导入模块时,咱们须要初始化tkinter。为此,咱们创立Tk( )
根窗口小部件。当初,这将创立咱们的主GUI窗口,咱们将在其中增加小部件。此时,咱们的主窗口只有标题栏。
咱们应该只为咱们的应用程序创立一个窗口,并且必须在增加任何其余小部件之前创立该窗口。之后,咱们应用root.mainloop( )
。除非输出,否则不会显示咱们刚刚创立的主窗口mainloop
。当咱们按下敞开按钮时,咱们的程序将退出主循环。在按下敞开按钮之前,咱们的应用程序将始终运行。
用于创立简略的tkinter窗口的代码:
#import required librariesfrom tkinter import *# initialize tkinter :root = Tk()# enter the main Loop :root.mainloop()
Tkinter的小部件与示例
- 按钮:显示按钮。
- 画布:绘制形态。
- 复选框:将多个选项显示为复选框。
- 输出:承受用户的单行输出。
- 框架:组织其余小部件。
- 标签:为其余小部件增加题目。
- 列表框:向用户提供选项列表。
- 菜单按钮:在咱们的应用程序中显示菜单。
- 菜单:向用户提供各种命令。
- 音讯:显示多行文本字段。
- 单选按钮:将选项数量显示为单选按钮。
- 比例尺:提供滑块。
- 滚动条:增加滚动性能。
- 文字:以多行显示文字。
- 顶层:提供独自的窗口容器。
- Spinbox:从固定输出值中抉择。
- PanedWindow:程度或垂直排列小部件。
- LabelFrame:以简单的构造提供空间。
- tkMessageBox:在应用程序中显示音讯框。
当初,咱们将简要介绍in out应用程序中须要的一些小部件。请记住,这里咱们将以最简略的示例演示该小部件。每个小部件中还有许多可用性能。在开发游戏时,咱们会看到其中的一些。
一些Tkinter小部件示例
按钮: 按钮小部件用于在咱们的应用程序中显示按钮。通常,当咱们按下一个按钮时,将有一个与之关联的命令。
# Import required libraries :from tkinter import *# Initialize tkinter :root = Tk()# Adding widgets :# Add button :btn = Button(root,text="PRESS ME",command=lambda:press())# Place button in window : btn.grid(row=0,column=0)# Define the function :def press() lbl = Label(root,text="You Pressed The Button") lbl.grid(row=0,column=1)# Enter the main Loop : root.mainloop()
标签:标签小部件用于为咱们应用程序中的其余小部件提供单行题目。
# Import required libraries :from tkinter import *# Initialize tkinter :root = Tk()# Adding widgets :# Add label :lbl = Label(root,text="This is label")# Place the button on window :lbl.grid(row=0,column=1)# Enter the main Loop :root.mainloop()
画布:画布小部件用于绘制各种形态。
# Import required libraries :from tkinter import *# Initialize tkinter :root = Tk()# Adding widgets : # Add canvas : # Create canvas object : c = Canvas(root,bg="3389db",height=250,width-300)# Draw a straight line :line = c.create_line(0,0,50,50)# To fit the line in the windowc.pack()# Enter the main looproot.mainloop()
CheckButton:咱们应用checkbutton显示可供用户应用的多个选项。在这里,用户能够抉择多个选项。
# Import required libraries :from tkinter import *# Initialize tkinter :root = Tk()# Adding widgets : # Add checkbutton : # IntVar() hold integers# Default value is 0# If checkbox is marked, this will change to 1checkvar1 = IntVar()checkvar2 = IntVar()# Create checkbutton c1 = Checkbutton(root,text="BMW", variable=checkvar1)c2 = Checkbutton(root,text="Audi",variable=checkbar2)# To fit in the main windowc1.grid(row=0,column=0)c2.grid(row=1,column=0)# Enter the main Looproot.mainloop()
** Entry小部件用于承受用户的单行输出。
# Import required libraries from tkinter import *# Initialize tkinterroot = Tk()# Adding widgets # Label lbl = Label(root,text="Enter your name:")lbl.grid(row=0,column=0)# Entry e = Entry(root)e.grid(row=0,column=1)# Enter the main Looproot.mainloop()
框架:用作容器小部件,以组织同一应用程序中的其余小部件
# Import required libraries from tkinter import *# Initialize tkinterroot = Tk()# Adding widgets frame = Frame(root)frame.pack()# Add button on LeftA = Button(frame,text="A")A.pack(side = LEFT)# Add button on Right B = Button(frame,text="B")B.pack(side = RIGHT)# Enter the main Looproot.mainloop()
列表框:用于向用户提供选项列表。
# Import required libraries from tkinter import *# Initialize tkinterroot = Tk()# Adding widgets # Create Listbox : Lb = Listbox(root)# Add items in listLb.insert(1,"A")Lb.insert(2,"B")Lb.insert(3,"C")Lb.insert(4,"D")# Place listbox on window Lb.grid(row=0,column=0)# Enter the main Looproot.mainloop()
从头开始构建数字猜谜游戏
分步演练
当用户运行程序时,咱们的代码将生成一个介于0到9之间的随机数。用户将不晓得随机生成的数字。当初,用户必须猜想随机生成的数字的值。用户在输入框中输出值。之后,用户将按下查看按钮。该按钮将触发性能。该性能将检查用户输出的号码是否与随机生成的号码匹配。如果猜想的数字正确,则程序将显示正确的标签和理论数字(在这种状况下,该数字将与猜想的数字雷同)。
当初,如果猜想的数字小于随机生成的数字,则咱们的程序将显示TOO LOW标签,并且这还将革除输入框,以便用户能够输出新的数字。
如果猜中的数字高于理论数字,则咱们的程序将显示TOO HIGH标签,并革除输入框。这样,用户能够持续猜想正确的数字。
如果标签显示TOO HIGH,则用户应该输出比他们猜测的数字低的数字。如果标签显示TOO LOW,则用户应该输出比他们第一次猜想的数字更大的数字。
咱们的程序还将计算用户猜想正确数字所需的尝试次数。当用户最终做出正确的猜想时,它将显示总尝试次数。
如果用户想玩新游戏,则必须按下主敞开按钮。如果用户在咱们的应用程序中按下“ 敞开”按钮,则他们将齐全退出游戏。
只需简略的步骤即可:
- 运行应用程序。
- 输入您的猜想。
- 按下查看按钮。
- 如果标签显示不正确,请猜想一个新数字。
- 如果标签显示正确,则显示尝试次数。
- 按下主敞开按钮以新号码从新开始游戏。
- 从咱们的应用程序中按下敞开按钮以齐全退出游戏。
咱们将逐渐向您展现如何应用Python tkinter构建上述游戏。
图片素材在这里IT小站,此处下载数字猜谜游戏素材
步骤1:导入所需的库
# import required libraies :from tkinter import * # to add widgetsimport random # to generate a random numberimport tkinter.font as font # to change properties of fontimport simpleaudio as sa # to play sound files
步骤2:建设主Tkinter视窗
want_to_play = True while want_to_play==True: root = Tk() root.title("Guess The Number!") root.geometry('+100+0') root.configure(bg="#000000") root.resizable(width=False,height=False) root.iconphoto(True,PhotoImage(file="surprise.png"))
- 首先,咱们创立一个名为的变量
want_to_play
,并将其值设置为True
。当变量设置为时,咱们的程序将生成一个新窗口True
。当用户按下主敞开按钮时,它将退出循环,然而在这里,咱们将变量设置为True
,因而它将应用新生成的数字创立另一个窗口。 root = Tk( )
:用于初始化咱们的tkinter模块。root.title( )
:咱们应用它来设置应用程序的题目。root.geometry( )
:咱们应用它来指定咱们的应用程序窗口将在哪个地位关上。root.configure( )
:咱们应用它来指定应用程序的背景色。root.resizable( )
:在这里咱们应用它来避免用户调整主窗口的大小。root.iconphoto( )
:咱们应用它来设置应用程序窗口标题栏中的图标。咱们将第一个参数设置为True
。
步骤3:导入声音文件
# to play sound files start = sa.WaveObject.from_wave_file("Start.wav")one = sa.WaveObject.from_wave_file("Win.wav")two = sa.WaveObjet.from_wave_file("Lose.wav")three = sa.WaveObject.from_wave_file("Draw.wav")start.play()
当初,咱们将应用一些将在各种事件中播放的声音文件。当咱们的程序启动时,它将播放开始文件。当用户的猜想正确,用户的猜想谬误以及用户敞开应用程序时,咱们将别离播放其余三个文件。须要留神的一件事是它仅承受.wav
文件。首先,咱们须要将声音文件加载到对象中。而后咱们能够.play( )
在须要时应用办法播放它。
步骤4:为咱们的应用程序加载图像
咱们将在应用程序中应用各种图像。要首先应用这些图像,咱们须要加载这些图像。在这里,咱们将应用PhotoImage类加载图像。
# Loading imagesCheck = PhotoImage(file="Check_5.png")High = PhotoImage(file="High_5.png")Low = PhotoImage(file="Low_5.png")Correct = PhotoImage(file="Correct_5.png")Surprise = PhotoImage(file="Surprise.png")your_choice = PhotoImage(file="YOUR_GUESS.png")fingers = PhotoImage(file="fingers.png")close = PhotoImage(file="Close_5.png")
步骤5:产生随机数
在这里,咱们将生成1–9之间的随机数。咱们将应用随机模块生成1–9之间的随机整数。
# generating random numbernumber = random.randint(1,9)
步骤6:批改字体
在这里,咱们将应用字体模块来更改应用程序中的字体。
# using font module to modify fontsmyFont = font.Font(family='Helvetica',weight='bold')
步骤7:增加小部件
在这里,咱们增加了应用程序的前两个小部件。请留神,输入框位于第2行,因为咱们在第1行中增加了空格。在这里,咱们将在标签中应用图像文件。咱们用于.grid( )
指定特定小部件的地位。
# Creating first labellabel = Label(root,image=your_choice)label.grid(row=0,column=1)# Creating the entry box e1 = Entry(root,bd=5,width=13,bg="9ca1db",justify=CENTER,font=myFont)e1.grid(row=2,column=1)
步骤8:增加其余小部件
在这里,咱们将增加其余一些小部件,例如按钮和标签。将有两个按钮,一个用于查看值,另一个用于永恒敞开窗口。第二个标签将显示用户猜想的值是正确还是高还是低。它将相应地显示标签。如果用户的猜想正确,第三个标签将显示正确的数字。
第四个标签显示用户猜想正确值所破费的尝试总数。在这里请留神,这两个按钮将触发命令。在接下来的几点中,咱们将对此进行钻研。
# Creating check button :b1 = Button(root,image=Check,command=lambda:show())b1.grid(row=4,column=3)# Creating close button :b2 = Button(root,image=close,command=lambda:reset())#Creaating second label :label2 = Label(root,image=fingers)label2.grid(row=6,column=1)#Creating third label :label3 = Label(root,image=Surprise)label3.grid(row=10,column=1)#Creating fourth label :label4= Label(root,text="ATTEMPTS : ",bd=5,width=13,bg="#34e0f2",justify=CENTER,font=myFont)label4.grid(row=12,column=1)
步骤9:显示正确的图像并将计数器设置为尝试值
当用户的猜想正确时,咱们将在此处显示正确的数字图像。咱们的数字存储形式如下:
- 1.png
- 2.png
- 3.png
- …
- 100.png
因而,咱们的程序将采纳理论的数字,并在其中增加.png字符串并关上该文件。咱们还将设置计数器以计算尝试值。它将存储尝试猜想正确数字所需的尝试次数值。
# to display the correct imagenum = PhotoImage(file = str(number)+str(".png"))# Set the count to 0count = 0
步骤10:当咱们按下查看按钮时将触发的性能
在这里,每当用户按下查看按钮时,尝试次数的计数值将减少一。而后,咱们将用户输出的值存储在名为answer的变量中。而后,咱们将检查用户是否尚未输出任何值,并按下查看按钮,它将转到reset()
性能,应用程序将敞开。
当初,咱们必须将用户输出的值转换为整数,以便将其与理论数字进行比拟。
def show(): #Increase the count value as the user presses check button. global count count = count+1 #Get the value entered by user. answer = e1.get() #If the entry value is null the goto reset() function. if answer=="": reset() #Convert it to int for comparision. answer = int(e1.get()) if answer > number: #Play sound file. two.play() #Change the label to Too High. label2.configure(image=High) #Calls all pending idle tasks. root.update_idletasks() #Wait for 1 second. root.after(1000) #Clear the entry. e1.delete(0,"end") #Change the label to the original value. label2.configure(image=fingers) elif answer < number: #Play sound file. two.play() #Change the label to Too Low. label2.configure(image=Low) #Calls all pending idle tasks. root.update_idletasks() #Wait for 1 second. root.after(1000) #Clear the entry. e1.delete(0,"end") #Change the label to the original value. label2.configure(image=fingers) else: #Play sound file. one.play() #Show the CORRECT image. label2.configure(image=Correct) #Show the correct number. label3.configure(image=num) #Show the number of attempts. label4.configure(text="ATTEMPTS : "+str(count))
步骤11:“敞开”按钮将触发reset()
性能
此函数会将want_to_play
变量设置为,False
以便咱们的应用程序敞开并且不会再次启动。而后它将敞开咱们的应用程序的主窗口。
# define reset() function def reset(): # Play sound file three.play() # Change the variable to false global want_to_play want_to_play = false # Close the tkinter window root.destroy()
步骤12:主循环
咱们必须进入主循环能力运行程序。如果咱们的程序没有这一行,那么它将行不通。咱们的程序将放弃在主循环中,直到咱们按下敞开按钮。
# Enter the mainLooproot.mainloop()
残缺代码
#Import required libraries :from tkinter import *import randomimport tkinter.font as fontimport simpleaudio as sawant_to_play = Truewhile want_to_play==True: root = Tk() root.title("Guess The Number!") root.geometry('+100+0') root.configure(bg="#000000") root.resizable(width=False,height=False) root.iconphoto(True,PhotoImage(file="surprise.png")) #To play 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("Draw.wav") start.play() #Loading images : Check = PhotoImage(file="Check_5.png") High = PhotoImage(file="High_5.png") Low = PhotoImage(file="Low_5.png") Correct = PhotoImage(file="Correct_5.png") Surprise= PhotoImage(file ="Surprise.png") your_choice = PhotoImage(file="YOUR_GUESS.png") fingers = PhotoImage(file = "Fingers.png") close = PhotoImage(file="Close_5.png") #To have space between rows. root.grid_rowconfigure(1, minsize=30) root.grid_rowconfigure(3, minsize=30) root.grid_rowconfigure(5, minsize=30) root.grid_rowconfigure(9, minsize=30) root.grid_rowconfigure(11, minsize=30) #Generating random number : number = random.randint(1,9) #Using font module to modify the fonts : myFont = font.Font(family='Helvetica',weight='bold') #Creating the first label : label = Label(root,image=your_choice) label.grid(row=0,column=1) #Creating the entry box : e1 = Entry(root,bd=5,width=13,bg="#9ca1db",justify=CENTER,font=myFont) e1.grid(row=2,column=1) #Creating check button : b1 = Button(root,image=Check,command=lambda:show()) b1.grid(row=4,column=3) #Creating close button : b2 = Button(root,image=close,command=lambda:reset()) b2.grid(row=4,column=0) #Creaating second label : label2 = Label(root,image=fingers) label2.grid(row=6,column=1) #Creating third label : label3 = Label(root,image=Surprise) label3.grid(row=10,column=1) #Creating fourth label : label4= Label(root,text="ATTEMPTS : ",bd=5,width=13,bg="#34e0f2",justify=CENTER,font=myFont) label4.grid(row=12,column=1) #To display the correct image : num = PhotoImage(file=str(number)+str(".png")) #Set the count to 0. #It stores the attempt value. count = 0 def show(): #Increase the count value as the user presses check button. global count count = count+1 #Get the value entered by user. answer = e1.get() #If the entry value is null the goto reset() function. if answer=="": reset() #Convert it to int for comparision. answer = int(e1.get()) if answer > number: #Play sound file. two.play() #Change the label to Too High. label2.configure(image=High) #Calls all pending idle tasks. root.update_idletasks() #Wait for 1 second. root.after(1000) #Clear the entry. e1.delete(0,"end") #Change the label to the original value. label2.configure(image=fingers) elif answer < number: #Play sound file. two.play() #Change the label to Too Low. label2.configure(image=Low) #Calls all pending idle tasks. root.update_idletasks() #Wait for 1 second. root.after(1000) #Clear the entry. e1.delete(0,"end") #Change the label to the original value. label2.configure(image=fingers) else: #Play sound file. one.play() #Show the CORRECT image. label2.configure(image=Correct) #Show the correct number. label3.configure(image=num) #Show the number of attempts. label4.configure(text="ATTEMPTS : "+str(count)) #Define reset() function : def reset(): #Play the sound file. three.play() #Change the variable to false. global want_to_play want_to_play = False #Close the tkinter window. root.destroy() #Enter the mainloop : root.mainloop()