tkinter比较常用的组件

1.输入框组件

输入框(Entry)用来输入单行内容,可以方便地向程序传递用户参数。这里通过一个转换摄氏度和华氏度的小程序来演示该组件的使用。

import tkinter as tk
def btnHelloClicked():
    cd = float(entryCd.get())
    labelHello.config(text="%.2f°C = %.2f°F" % (cd, cd * 1.8 + 32))
root = tk.Tk()
root.title("Entry Test")
labelHello = tk.Label(root, text="Convert °C to °F...", height=5, width=20, fg="blue")
labelHello.pack()
entryCd = tk.Entry(root, text="0")
entryCd.pack()
btnCal = tk.Button(root, text="Calculate", command=btnHelloClicked)
btnCal.pack()
root.mainloop()
View Code

本例的代码从1.2.1中修改而来,并新建了一个Entry组件entryCd,text参数设置了输入框的默认值为“0”。当按钮按下后,通过entryCd.get()获取输入框中的文本内容,该内容为字符串类型,需要通过float()函数转换成数字,自后再进行换算并更新label显示内容。

表3 Entry组件常用参数

参数

描述

height

组件的高度(所占行数)

width

组件的宽度(所占字符个数)

fg

前景字体颜色

bg

背景颜色

show

将Entry框中的文本替换为指定字符,用于输入密码等,如设置 show="*"

state

设置组件状态,默认为normal,可设置为:disabled—禁用组件,readonly—只读

2.单选、复选框

单选框(Radiobutton)和复选框(Checkbutton)分别用于实现选项的单选和复选功能。本例中的代码实现了通过单选框、复选框设置文字样式的功能。

import tkinter as tk
def colorChecked():
    labelHello.config(fg=color.get())
def typeChecked():
    textType = typeBlod.get() + typeItalic.get()
    if textType == 1:
        labelHello.config(font=("Arial", 12, "bold"))
    elif textType == 2:
        labelHello.config(font=("Arial", 12, "italic"))
    elif textType == 3:
        labelHello.config(font=("Arial", 12, "bold italic"))
    else:
        labelHello.config(font=("Arial", 12))
root = tk.Tk()
root.title("Radio & Check Test")
labelHello = tk.Label(root, text="Check the format of text.", height=3, font=("Arial", 12))
labelHello.pack()
color = tk.StringVar()#定义一个字符串变量
tk.Radiobutton(root, text="Red", variable=color, value="red",
               command=colorChecked).pack(side=tk.LEFT)
tk.Radiobutton(root, text="Blue", variable=color, value="blue",
               command=colorChecked).pack(side=tk.LEFT)
tk.Radiobutton(root, text="Green", variable=color, value="green",
               command=colorChecked).pack(side=tk.LEFT)
typeBlod = tk.IntVar()#定义整型变量
typeItalic = tk.IntVar()#定义整型变量
tk.Checkbutton(root, text="Blod", variable=typeBlod, onvalue=1,
               offvalue=0, command=typeChecked).pack(side=tk.LEFT)
                #onvalue代表复选框选中时整型变量的值
tk.Checkbutton(root, text="Italic", variable=typeItalic, onvalue=2,
               offvalue=0, command=typeChecked).pack(side=tk.LEFT)
root.mainloop()
View Code

在代码中,文字的颜色通过Radiobutton来选择,同一时间只能选择一个颜色。在三个Red、Blue和Green三个单选框中,定义了同样的变量参数color,选择不同的单选框会为该变量赋予不同的字符串值,内容即为对应的颜色。

任何单选框被选中都会触发colorChecked()函数,将标签修改为对应单选框表示的颜色。

表4 Radiobutton组件常用参数

参数

描述

variable

单选框索引变量,通过变量的值确定哪个单选框被选中。一组单选框使用同一个索引变量

value

单选框选中时变量的值

command

单选框选中时执行的命令(函数)

文字的粗体、斜体样式则由复选框实现,分别定义了typeBlod和typeItalic变量来表示文字是否为粗体和斜体。

当某个复选框的状态改变时会触发typeChecked()函数。该函数负责判断当前那些复选框被选中,并将字体设置为对应的样式。

表5 Checkbutton组件常用参数

参数

描述

variable

复选框索引变量,通过变量的值确定哪些复选框被选中。每个复选框使用不同的变量,使复选框之间相互独立

onvalue

复选框选中(有效)时变量的值

offvalue

复选框未选中(无效)时变量的值

command

复选框选中时执行的命令(函数)

3.消息窗口

消息窗口(messagebox)用于弹出提示框向用户进行告警,或让用户选择下一步如何操作。消息框包括很多类型,常用的有info、warning、error、yeno、okcancel等,包含不同的图标、按钮以及弹出提示音。下面的代码演示了各消息框的运行效果,大家可以自己一一尝试。

import tkinter as tk
from tkinter import messagebox as msgbox
def btn1_clicked():
    msgbox.showinfo("Info", "从前慢!")
def btn2_clicked():
    msgbox.showwarning("Warning", "不要在月亮上喝酒!")
def btn3_clicked():
    msgbox.showerror("Error", "输入可能有错误!")
def btn4_clicked():
    msgbox.askquestion("Question", "你要吃香蕉还是苹果?")
def btn5_clicked():
    msgbox.askokcancel("OkCancel", "确定穿越到唐朝吗?")
def btn6_clicked():
    msgbox.askyesno("YesNo", "确定去买衣裳?")
def btn7_clicked():
    msgbox.askretrycancel("Retry", "别气馁,再来一次!")
root = tk.Tk()
root.title("消息框测试")
btn1 = tk.Button(root, text="showinfo", command=btn1_clicked)
btn1.pack(fill=tk.X)
btn2 = tk.Button(root, text="showwarning", command=btn2_clicked)
btn2.pack(fill=tk.X)
btn3 = tk.Button(root, text="showerror", command=btn3_clicked)
btn3.pack(fill=tk.X)
btn4 = tk.Button(root, text="askquestion", command=btn4_clicked)
btn4.pack(fill=tk.X)
btn5 = tk.Button(root, text="askokcancel", command=btn5_clicked)
btn5.pack(fill=tk.X)
btn6 = tk.Button(root, text="askyesno", command=btn6_clicked)
btn6.pack(fill=tk.X)
btn7 = tk.Button(root, text="askretrycancel", command=btn7_clicked)
btn7.pack(fill=tk.X)
root.mainloop()
View Code

4.绘图组件

绘图组件(Canvas)可以在GUI中实现2D图形的绘制,相当于画图板。组件内置了多种绘图函数,可以通过简单的2D坐标绘制直线、矩形、圆形、多边形等。本例代码演示了Canvas组件的绘图功能,更多的绘图函数可以查阅Canvas的参考页面。

import tkinter as tk
def drawCircle(self, x, y, r, **kwargs):
    return self.create_oval(x - r, y - r, x + r, y + r, **kwargs)
root = tk.Tk()
root.title("画布测试")
cvs = tk.Canvas(root, width=600, height=400)
cvs.pack()
cvs.create_line(50, 50, 50, 300)
cvs.create_line(100, 50, 200, 300, fill="red", dash=(4, 4), arrow=tk.LAST)
cvs.create_rectangle(200, 50, 400, 200, fill="blue")
cvs.create_oval(450, 50, 550, 200, fill="green")
drawCircle(cvs, 450, 300, 50, fill="red")
cvs.create_polygon(200, 250, 350, 250, 350, 350, 220, 300, fill="yellow")
root.mainloop()
View Code

绘图函数的参数都比较好理解,包括基本的坐标和颜色、线型等附加参数。

直线(line),即线段,通过两个端点定义。坐标顺序为x1、y1、x2、y2。

矩形(rectangle)通过对角线上的两个点来定义。

需要注意的是Canvas中没有画圆函数,这里通过绘制椭圆间接实现了绘制圆形的函数drawCircle()。椭圆(oval)是通过外切矩形的对角线两点来定义的。

5.hello tkinter

首先介绍一个tkinter的基本例子,在IDLE中新建hello_tkinter.py,代码如下:

import tkinter as tk
# 建立tkinter窗口,设置窗口标题
root = tk.Tk()
root.title("Hello Test")
# 在窗口中创建标签
labelHello = tk.Label(root, text="Hello Tkinter!")
labelHello.pack()
# 运行并显示窗口
root.mainloop()
View Code

表1 Label组件常用参数

参数

描述

height

组件的高度(所占行数)

width

组件的宽度(所占字符个数)

fg

前景字体颜色

bg

背景颜色

justify

多行文本的对齐方式,可选参数为: LEFT、 CENTER、RIGHT

padx

文本左右两侧的空格数(默认为1)

pady

文本上下两侧的空格数(默认为1)

6.按钮组件

按钮组件(Button)是tkinter最常用的图形组件之一,通过Button可以方便地与用户进行交互。下列代码实现了通过触发按钮事件(按下按钮)来执行指定操作(改变标签内容)的例子。

import tkinter as tk
def btnHelloClicked():
    labelHello.config(text="Hello tkinter!")
root = tk.Tk()
root.title("Button Test")
labelHello = tk.Label(root, text="Press the button...", height=5, width=20, fg="blue")
labelHello.pack()
btn = tk.Button(root, text="Hello", command=btnHelloClicked)
btn.pack()
root.mainloop()
View Code

代码中定义了btnHelloClicked()函数,并通过给Button的command属性赋值来指定按钮按下时执行btnHelloClicked()函数中的代码的功能。在该函数中,通过labelHello.config()更改了label的text参数,即更改了标签的文字内容。

表2 Button组件基本参数

参数

描述

height

组件的高度(所占行数)

width

组件的宽度(所占字符个数)

fg

前景字体颜色

bg

背景颜色

activebackground

按钮按下时的背景颜色

activeforeground

按钮按下时的前景颜色

justify

多行文本的对齐方式,可选参数为: LEFT、 CENTER、RIGHT

padx

文本左右两侧的空格数(默认为1)

pady

文本上下两侧的空格数(默认为1)

以上内容来自于:https://blog.csdn.net/wuxiushu/article/details/52516652

原文地址:https://www.cnblogs.com/yibeimingyue/p/9395118.html