Tkinter 控件

文章更新于:2020-04-25
注0:原英文教程地址:zetcode.com
注1:Introduction to Tkinter 参见:关于Tkinter的介绍
注2:Layout management in Tkinter 参见:Tkinter布局管理器
注3:Tkinter widgets 参见:Tkinter 控件

Tkinter widgets

In this part of the Tkinter tutorial, we will cover some basic Tkinter widgets. We work with the following widgets: Checkbutton, Label, Scale, and Listbox.

在本章节,我们讲一些基本的 Tkinter 控件。
我们将使用到:CheckbuttonLabelScaleListbox 控件。

Widgets are basic building blocks of a GUI application. Over the years, several widgets became a standard in all toolkits on all OS platforms; for example a button, a check box or a scroll bar. Some of them might have different names. For instance, a check box is called a check button in Tkinter. Tkinter has a small set of widgets which cover basic programming needs. More specialised widgets can be created as custom widgets.

控件是图形化程序的一个基本块。
很多年来,很多控件都已经成为了所有操作系统的标准工具集。
比如说:Tkinter 的一个复选框。

Tkinter 拥有一个程序最少需要的控件集。
更专业的控件可以自己定义创建。

Tkinter Checkbutton

Checkbutton is a widget that has two states: on and off. The on state is visualized by a check mark. (Some themes may have different visuals.) It is used to denote some boolean property. The Checkbutton widget provides a check box with a text label.

一个复选框控件有两种状态:开和关。
当开的时候你可以看见一个复选标记(不同的主题样式也不一样)。
它可以用来指示一些布尔量。
复选框控件提供了一个复选方框和文字标签。

#!/usr/bin/env python3

"""
ZetCode Tkinter tutorial

This program toggles the title of the
window with the Checkbutton widget.

Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""

from tkinter import Tk, Frame, Checkbutton
from tkinter import BooleanVar, BOTH

class Example(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.master.title("Checkbutton")

        self.pack(fill=BOTH, expand=True)
        self.var = BooleanVar()

        cb = Checkbutton(self, text="Show title",
            variable=self.var, command=self.onClick)
        cb.select()
        cb.place(x=50, y=50)


    def onClick(self):

        if self.var.get() == True:
            self.master.title("Checkbutton")
        else:
            self.master.title("")


def main():

    root = Tk()
    root.geometry("250x150+300+300")
    app = Example()
    root.mainloop()


if __name__ == '__main__':
    main()

In our example, we place a check button on the window. The check button shows or hides the title of the window.

在我们这个例子中,我们放置了一个复选框在窗口上。
这个复选框决定了窗口的标题是否显示。

self.var = BooleanVar()

We create an BooleanVar object. It is a value holder for Boolean values for widgets in Tkinter.

我们创建了一个布尔变量对象。
它是控件布尔值的值。

cb = Checkbutton(self, text="Show title",
    variable=self.var, command=self.onClick)

An instance of the Checkbutton is created. The value holder is connected to the widget via the variable parameter. When we click on the check button, the onClick() method is called. This is done with the command parameter.

这里创建了一个复选框的示例。
绑定在复选框上的值由 variable 来指定。
当我们点击复选框的时候,onClick()方法将被调用。
这些由 command 参数指定。

cb.select()

刚开始的时候,标题是显示的。
所以我们使用 select() 方法先让复选框选上。

if self.var.get() == True:
    self.master.title("Checkbutton")
else:
    self.master.title("")

Inside the onClick() method, we display or hide the title based on the value from the self.var variable.

onClick() 方法中,我们根据 self.var 的值来决定是否显示标题。

在这里插入图片描述

Tkinter Label

The Label widget is used to display text or images. No user interaction is available.

标签控件没有用户交互,只是用于显示文字或图片。

#!/usr/bin/env python3

"""
ZetCode Tkinter tutorial

In this script, we use the Label
widget to show an image.

Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""

from PIL import Image, ImageTk
from tkinter import Tk
from tkinter.ttk import Frame, Label
import sys

class Example(Frame):

    def __init__(self):
        super().__init__()

        self.loadImage()
        self.initUI()


    def loadImage(self):
        try:
            self.img = Image.open("tatras.jpg")

        except IOError:
            print("Unable to load image")
            sys.exit(1)


    def initUI(self):

        self.master.title("Label")

        tatras = ImageTk.PhotoImage(self.img)
        label = Label(self, image=tatras)

        # reference must be stored
        label.image = tatras

        label.pack()
        self.pack()


    def setGeometry(self):

        w, h = self.img.size
        self.master.geometry(("%dx%d+300+300") % (w, h))


def main():

    root = Tk()
    ex = Example()
    ex.setGeometry()
    root.mainloop()


if __name__ == '__main__':
    main()

在这个例子中,我们在窗口上显示了一张图片。

from PIL import Image, ImageTk

By default, the Label widget can display only a limited set of image types. To display a JPG image, we must use the PIL, Python Imaging Library module. Learn more about PIL with Pillow tutorial.

默认的,标签控件只能显示指定的一些图片类型。
比如显示 jpg 图片,我们需要使用 PIL 也就是 python 图片库模块。
更多内容可以访问 Pillow 教程

self.img = Image.open("tatras.jpg")

We create an Image from the image file in the current working directory.

我们从当前工作路径下的图片文件创建了 Image 图片对象。

tatras = ImageTk.PhotoImage(self.img)

We create a photo image from the image.

我们从图片对象创建了一个图片。

label = Label(self, image=tatras)

The photoimage is given to the image parameter of the label widget.

这个图片赋给了 label 控件的 image 参数。

label.image = tatras

In order not to be garbage collected, the image reference must be stored.

为了不被垃圾回收,图片引用必须被存储。

w, h = self.img.size
self.master.geometry(("%dx%d+300+300") % (w, h))

We make the size of the window to exactly fit the image size.

然后我们让窗口的大小刚好适应图片。

Tkinter Scale

Scale is a widget that lets the user graphically select a value by sliding a knob within a bounded interval. Our example will show a selected number in a label widget.

刻度尺是一个能让用户通过滑动滑块来选择一个值的控件。
这里我们展示一个选择标签数字的例子。

#!/usr/bin/env python3

"""
ZetCode Tkinter tutorial

In this script, we show how to
use the Scale widget.

Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""

from tkinter import Tk, BOTH, IntVar, LEFT
from tkinter.ttk import Frame, Label, Scale, Style

class Example(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.master.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)

        scale = Scale(self, from_=0, to=100,
            command=self.onScale)
        scale.pack(side=LEFT, padx=15)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack(side=LEFT)


    def onScale(self, val):

        v = int(float(val))
        self.var.set(v)


def main():

    root = Tk()
    ex = Example()
    root.geometry("250x100+300+300")
    root.mainloop()


if __name__ == '__main__':
    main()

We have two widgets in the above script: a scale and a label. A value from the scale widget is shown in the label widget.

在上面这个脚本中,我们设置了两个控件:标签和刻度尺。
刻度尺的值显示在标签控件中。

scale = Scale(self, from_=0, to=100,
    command=self.onScale)

A Scale widget is created. We provide the lower and upper bounds. The from is a regular Python keyword that is why there is an underscore after the first parameter. When we move the knob of the scale, the onScale() method is called.

这创建了一个刻度尺控件。
我们提供了最大和最小值两个限制。
from_ 参数加了下划线是因为 frompython 的关键字。
当我们在刻度尺上滑动滑块的时候, onScale() 方法被调用。

self.var = IntVar()
self.label = Label(self, text=0, textvariable=self.var)

An integer value holder and label widget are created. Value from the holder is shown in the label widget.

这里创建了一个值和一个标签控件。
值被显示在标签控件中。

def onScale(self, val):

    v = int(float(val))
    self.var.set(v)

The onScale() method receives a currently selected value from the scale widget as a parameter. The value is first converted to a float and then to integer. Finally, the value is set to the value holder of the label widget.

这个 onScale() 方法接收一个当前刻度尺选中的值作为参数。
然后将这个值从 float 转换为 int
最后这个值被显示在标签控件中。

在这里插入图片描述

Tkinter Listbox

Listbox is a widget that displays a list of objects. It allows the user to select one or more items.

列表框一个显示列表对象的控件。
它允许用户选个一个或多个项目。

#!/usr/bin/env python3

"""
ZetCode Tkinter tutorial

In this script, we show how to
use the Listbox widget.

Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""

from tkinter import Tk, BOTH, Listbox, StringVar, END
from tkinter.ttk import Frame, Label

class Example(Frame):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.master.title("Listbox")

        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss',
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)

        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack()


    def onSelect(self, val):

        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)

        self.var.set(value)


def main():

    root = Tk()
    ex = Example()
    root.geometry("300x250+300+300")
    root.mainloop()


if __name__ == '__main__':
    main()

In our example, we show a list of actresses in the Listbox. The currently selected actress is displayed in a label widget.

在这个例子中,
我们显示了演员列表的内容在列表框中。
当前选中的演员显示在标签控件中。

acts = ['Scarlett Johansson', 'Rachel Weiss',
    'Natalie Portman', 'Jessica Alba']

This is a list of actresses to be shown in the listbox.

这是显示在列表框中的演员名字列表。

lb = Listbox(self)
for i in acts:
    lb.insert(END, i)

We create an instance of the Listbox and insert all the items from the above mentioned list.

我们创建了一个列表框的示例,
然后将上面我们提到的列表内容插入进去。

lb.bind("<<ListboxSelect>>", self.onSelect)

When we select an item in the listbox, the <> event is generated. We bind the onSelect() method to this event.

当我们在列表框中选择一个项目的时候,
这个 <<ListboxSelect>> 事件被生成。
我们将 onSlect() 方法绑定到这个事件上。

self.var = StringVar()
self.label = Label(self, text=0, textvariable=self.var)

A label and its value holder is created. In this label we will display the currently selected item.

一个标签和它的值容器被创建。
在这个标签中,我们显示当前被选中的项目。

sender = val.widget

We get the sender of the event. It is our listbox widget.

我们指定事件的触发器,他就是列表框控件。

idx = sender.curselection()

We find out the index of the selected item using the curselection() method.

我们获取被选中项目的索引值,然后将它用于触发事件。

value = sender.get(idx)

The actual value is retrieved with the get() method, which takes the index of the item.

我们使用 get() 方法获取索引值,也就是项目的索引。

self.var.set(value)

Finally, the label is updated.

最后,标签的值被更新。

在这里插入图片描述

In this part of the Tkinter tutorial, we have presented several Tkinter widgets.

在本章节,我们介绍了更多的 Tkinter 控件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值