为初学者逐步使用tkinter在python上构建gui

    科技2025-03-23  20

    In this post, I’m going to show you how to build a simple GUI App using Python’s Tkinter. By the end of this short tutorial, you should be able to create a simple Python App with buttons and data entries and use them to do simple functions.

    在本文中,我将向您展示如何使用Python的Tkinter构建一个简单的GUI App。 在本简短教程结束时,您应该能够创建带有按钮和数据条目的简单Python应用程序,并使用它们执行简单的功能。

    Before you start reading, you will need to install Tkinter and open a new IDLE on your local device. This tutorial is based on Python 3.6.

    在开始阅读之前,您需要安装Tkinter并在本地设备上打开一个新的IDLE。 本教程基于Python 3.6。

    We first start by importing Tkinter and to make it easy, we give it a shorter name “tk”:

    我们首先从导入Tkinter开始,为了简单起见,我们给它起一个简短的名字“ tk”:

    import tkinter as tk

    The first step in creating an App with Tkinter is to define your main class that will inherit the attributes from Tkinter:

    使用Tkinter创建应用的第一步是定义将继承Tkinter属性的主类:

    import tkinter as tkclass Application(tk.Tk):

    Now you use the __init__ argument to initialize your app and add all the features that you need to be loaded once the app loads, similarly, we also initialize Tkinter:

    现在,您使用__init__参数初始化应用程序,并添加应用程序加载后需要加载的所有功能,类似地,我们还初始化了Tkinter:

    import tkinter as tkclass Application(tk.Tk): def __init__(self): tk.Tk.__init__(self)

    At this point, we have basically identified everything we need to create a GUI. Again, for the sake of this class, we don’t need to define a container and a dictionary because these are needed only if we want them to hold multiple frames for multiple windows. Instead, we will use the initial window of Tkinter as our App. So to test how that window will look like, we can run that code. To run the code and start our application, we should use the mainloop() method:

    至此,我们已经基本确定了创建GUI所需的一切。 同样,出于此类的考虑,我们不需要定义容器和字典,因为仅当我们希望它们为多个窗口容纳多个框架时才需要它们。 相反,我们将使用Tkinter的初始窗口作为我们的App。 因此,要测试该窗口的外观,我们可以运行该代码。 要运行代码并启动我们的应用程序,我们应该使用mainloop()方法:

    import tkinter as tkclass Application(tk.Tk): def __init__(self): tk.Tk.__init__(self)app = Application()app.mainloop()

    When we run that code, we should get the following window:

    运行该代码时,我们将获得以下窗口:

    Which will be the main window of our App.

    这将是我们应用程序的主窗口。

    Now, we can go ahead and do a little bit of customization for the App.

    现在,我们可以继续为该应用程序进行一些自定义。

    The main customization that we can do to our window is to decide on its size, we can do that using the “geometry” method provided by Tkinter:

    我们可以对窗口进行的主要自定义是确定其大小,我们可以使用Tkinter提供的“ geometry”方法来实现:

    import tkinter as tkclass Application(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.geometry('500x500')app = Application()app.mainloop()

    Here we assigned a size of 500 by 500 for the window of the App. Now, when we run the code, we should get this window that has a size of 500x500:

    在这里,我们为应用程序的窗口分配了500 x 500的大小。 现在,当我们运行代码时,我们应该获得一个大小为500x500的窗口:

    Another essential customization is the name of the App which can be done by using the “title” method:

    另一个重要的自定义项是应用程序的名称,可以使用“ title”方法来完成:

    import tkinter as tkclass Application(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.geometry('500x500') self.title('Your first App')app = Application()app.mainloop()

    Running that code:

    运行该代码:

    Now as we have our window ready, we can start having some fun with Tkinter main widgets.

    现在,当我们准备好窗口时,我们就可以开始使用Tkinter主窗口小部件了。

    A nice widget to start with is the “Label” widget. You can use the “Label” widget to add any text to your window.

    一个很好的小部件是“ Label”小部件。 您可以使用“标签”小部件向窗口中添加任何文本。

    The “Label” widget is simple, you just give it a name and then add the text that you want as a string argument in the “Label” and you can also specify the font size that you want:

    “标签”小部件很简单,您只需为其命名,然后将所需的文本作为字符串参数添加到“标签”中,还可以指定所需的字体大小:

    import tkinter as tkclass Application(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.geometry('500x500') self.title('Your first App') first_label = tk.Label(self, text = "I'm a cool App!!", font=10) first_label.pack(pady= 2, padx = 2)app = Application()app.mainloop()

    Note two things:

    注意两件事:

    You should use “ tk. “ before the name of the widget (e.g. tk.Label) so that Python knows that you are referring to the Label widget of Tkinter

    您应该使用“ tk。 在小部件名称(例如tk.Label)之前添加,以便Python知道您所引用的是Tkinter的Label小部件 After defining the widget, you must pack it to our window by using “ .pack” and then you can adjust its position by specifying (x, y) coordinates (padx = 3 , pady = 3)

    定义小部件后,必须使用“ .pack”将其打包到我们的窗口中,然后可以通过指定(x,y)坐标来调整其位置(padx = 3,pady = 3)

    Running the code:

    运行代码:

    The second widget we will introduce is the button widget. Buttons are an essential feature for Apps, here we will learn how to add them and how to use them.

    我们将介绍的第二个小部件是按钮小部件。 按钮是Apps的基本功能,在这里我们将学习如何添加按钮以及如何使用它们。

    Similar to the Label widget, the Button widget can be added by using “tk.Button”, adding its name as a string argument and then packing it to the window :

    与Label小部件类似,可以通过使用“ tk.Button”添加Button小部件,将其名称添加为字符串参数,然后将其打包到窗口中:

    import tkinter as tkclass Application(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.geometry('500x500') self.title('Your first App') first_label = tk.Label(self, text = "I'm a cool App!!", font=10) first_label.pack(pady= 2, padx = 2) first_button = tk.Button(self, text ="Hello World", command = hello) first_button.pack(pady= 5, padx = 5)app = Application()app.mainloop()

    Running the code:

    运行代码:

    Note that if we click on that button, nothing happens. Now the fun part is assigning functions to buttons. Buttons can actually call and run any function that you define in python. All you have to do is to write your function and then associate it to the button using the method “command = name of the function”. For example, let’s define a simple function that prints “Hello World” and call it “hello”:

    请注意,如果我们单击该按钮,则什么也不会发生。 现在,有趣的部分是为按钮分配功能。 按钮实际上可以调用并运行您在python中定义的任何函数。 您所要做的就是编写函数,然后使用“命令=函数名称”方法将其与按钮关联。 例如,让我们定义一个简单的函数,该函数打印“ Hello World”并将其称为“ hello”:

    import tkinter as tkclass Application(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.geometry('500x500') self.title('Your first App') first_label = tk.Label(self, text = "I'm a cool App!!", font=10) first_label.pack(pady= 2, padx = 2) first_button = tk.Button(self, text ="Hello World", command = hello) first_button.pack(pady= 5, padx = 5)def hello(): print("Hello World, I just built my first App!!!")app = Application()app.mainloop()

    As you can see, we assigned the command of the button to the function “hello”. Now when you run the code and click on the button, python should run the function “hello” and then you should get this output:

    如您所见,我们将按钮的命令分配给了函数“ hello”。 现在,当您运行代码并单击按钮时,python应该运行函数“ hello”,然后您将获得以下输出:

    Similarly, you can write any function and assign it to the button and when you click the button, it will just run that function.

    同样,您可以编写任何函数并将其分配给按钮,然后单击按钮,它将仅运行该函数。

    The last widget we will introduce is the Entry widget. Entry boxes is also a very important feature in building Apps especially when you want to make an interactive App that takes inputs from the users.

    我们将介绍的最后一个小部件是Entry小部件。 输入框也是构建应用程序时非常重要的功能,尤其是当您要制作一个需要用户输入的交互式应用程序时。

    Similar to the two widgets we introduced, the Entry widget can be added to the App by using “tk.Entry” and then packing it to the window, note that you can control the width of the entry box using “width ” argument:

    类似于我们介绍的两个小部件,可以使用“ tk.Entry”将Entry小部件添加到应用程序,然后将其打包到窗口,请注意,您可以使用“ width”参数控制输入框的宽度:

    import tkinter as tkclass Application(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.geometry('500x500') self.title('Your first App') first_label = tk.Label(self, text = "I'm a cool App!!", font=10) first_label.pack(pady= 2, padx = 2) first_button = tk.Button(self, text ="Hello World", command = hello) first_button.pack(pady= 5, padx = 5) first_entry = tk.Entry(self, width = 30) first_entry.pack(padx = 7, pady = 7)def hello(): print("Hello World, I just built my first App!!!")app = Application()app.mainloop()

    Running the code:

    运行代码:

    Now we have an entry box where users can add any inputs for us. To illustrate how that entry box works, let’s do an upgrade to the code. We will make the “Hello World” button take the input that the user adds and print it. To do that, as you might have expected, the button should ask the function “hello” to take the input from the entry box and print it. The attribute that imports the input from the entry box is “.get() “, So we can simply define any variable x and put x = first_entry.get() in our function:

    现在,我们有一个输入框,用户可以在其中为我们添加任何输入。 为了说明该输入框是如何工作的,让我们对代码进行升级。 我们将使“ Hello World”按钮接受用户添加的输入并进行打印。 为此,如您所料,按钮应要求“ hello”功能从输入框中获取输入并进行打印。 从输入框导入输入的属性是“ .get()”,因此我们可以简单地定义任何变量x并将x = first_entry.get()放入函数中:

    import tkinter as tkclass Application(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.geometry('500x500') self.title('Your first App') first_label = tk.Label(self, text = "I'm a cool App!!", font=10) first_label.pack(pady= 2, padx = 2) first_button = tk.Button(self, text ="Hello World", command = hello) first_button.pack(pady= 5, padx = 5) first_entry = tk.Entry(self, width = 30) first_entry.pack(padx = 7, pady = 7)def hello(): x = first_entry.get() print(x)app = Application()app.mainloop()

    However, if we run the code this way, we will get an error because “first_entry” is a widget inside the class Application and so it can’t be called in another function like that. There are several ways to solve this problem, but for simplicity, we can make “first_entry” an attribute for the class “Application” by adding “Application.” to “first_entry”, this way “first_entry” is an attribute of the class “Application” and it can be called inside the function “hello”:

    但是,如果我们以这种方式运行代码,则会收到错误消息,因为“ first_entry”是Application类中的一个小部件,因此无法在类似这样的其他函数中调用它。 解决此问题的方法有多种,但为简单起见,我们可以通过添加“ Application”使“ first_entry”成为“ Application”类的属性。 对于“ first_entry”,这种方式“ first_entry”是“ Application”类的一个属性,可以在函数“ hello”内部调用:

    import tkinter as tkclass Application(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.geometry('500x500') self.title('Your first App') first_label = tk.Label(self, text = "I'm a cool App!!", font=10) first_label.pack(padx = 3, pady = 3) first_button = tk.Button(self, text ="Hello World", command = hello) first_button.pack(padx= 5, pady = 5) Application.first_entry = tk.Entry(self, width = 30) Application.first_entry.pack(padx = 7, pady = 7)def hello(): x = Application.first_entry.get() print(x)app = Application()app.mainloop()

    Now if we run the code and type any input in the entry box, clicking on the “Hello World” button should print this input. One addition to make the application cooler is to add this line inside the “hello” function:

    现在,如果我们运行代码并在输入框中键入任何输入,则单击“ Hello World”按钮将打印此输入。 使应用程序更酷的另一项措施是在“ hello”函数中添加以下行:

    Application.first_entry.delete(0,tk.END)

    Application.first_entry.delete(0,tk.END)

    This line will delete the input that users enter in the entry box after importing it (so that the entry box is clean and ready for new entries).

    此行将在导入后删除用户在输入框中输入的输入(以便使输入框干净并准备好新输入)。

    Now you can add as many buttons and data entries as you want to your App and use them to do any task you want. Hope this tutorial was helpful.

    现在,您可以在应用程序中添加任意数量的按钮和数据条目,并使用它们执行所需的任何任务。 希望本教程对您有所帮助。

    翻译自: https://medium.com/swlh/build-a-gui-on-python-using-tkinter-from-scratch-step-by-step-for-beginners-69466223bcdf

    相关资源:四史答题软件安装包exe
    Processed: 0.926, SQL: 8