Python GUI design - option button, check box, frame Frame

Table of contents

1. Option button Radiobutton

1.1 Basic concept of option button

1.2 Apply the dictionary to the option button

1.3 Box option button

1.4 Create an option button with an image

2. Checkbox Checkbutton

3. Frame Frame

         3.1 Basic concepts of the framework

3.2 Label frame LabelFrame

3.2.1 Applying a label frame to a checkbox

3.2.2 Toplevel window Toplevel


1. Option button Radiobutton

1.1 Basic concept of option button

The Radio Button is called the option button, which originated from the radio button. In the radio era, the radio button can be used to select a specific channel. The biggest feature of the option button is that you can use the mouse to select this option in a stand-alone mode, and only one option can be selected at a time.

During program design, option buttons can be designed to be bound together with functions (methods), and when an appropriate option button is selected, related functions or methods can be automatically executed. In addition, there may be multiple groups of option buttons during program design. At this time, you can design a group of option buttons with a related variable, and use this variable to bind this group of option buttons. The syntax of Radiobutton() is as follows:

Radiobutton(父对象, options, ……)

The following are other commonly used options parameters in the Radiobutton() method:

activebackground

Background color when the mouse cursor is over the option button

activeforeground

The foreground color when the mouse cursor is over the option button

anchor

Controls the position of the option button if the space is larger than required, default is CENTER

bg

The background color of the label background or indicator

bitmap

bitmap image object

borderwidth or bd

The border width defaults to two pixels

command

This function is automatically executed when the user changes an option

cursor

Cursor shape when the mouse cursor is over an option button

fg

text foreground color

font

font

height

Number of lines of text on option buttons

hightlightbackground

Background color when the option button has focus

highlightcolor

The color when the option button has focus

image

Image object, if you want to create an option button with an image, you can use this parameter

indicatoron

When this value is 0, you can create a box option button

justify

When there are multiple lines of text, the alignment of the last line of text

Padx

The default is 1, you can set the interval between the option button and the text

Paddy

The default is 1, you can set the upper and lower spacing of the option button

selectcolor

The color of the option button when it is selected

selectimage

If you set the image option button, you can set a different image when the option button is selected

state

The default is state=NORMAL. If DISABLE is set, the option button will be displayed in grayscale to indicate that it is temporarily unavailable

text

text next to option button

textvariable

Display option button text as a variable

underline

You can set the number of text to be underlined

value

The value of the option button, which can distinguish the selected option button

variable

Set or get the currently selected radio button, its value type is usually IntVar or StringVar

width

The text width of the option button, if omitted, it will be automatically adjusted to the actual width

wraplength

Limit the number of characters per line, the default is 0, which means that only '\n' will wrap

The way to bind the whole group of option buttons is as follows:

var IntVar
rb1 = Radiobutton(root, …, variable = var, value = x1, …)

If you want to get the options selected by this group of option buttons in the future, you can use the get() method, which will return the value of the parameter value of the selected option, and the method set() can set the initial default value option

programming:

from tkinter import *

def printSelection():
	num = var.get()
	if num == 1:
		label.config(text = "你是男生")
	else:
		label.config(text = "你是女生")

root = Tk()
var = IntVar()			# 选项按钮绑定的变量
var.set(1)              # 默认选项是男生
label = Label(root, text = "这是预设,请选择", bg = "lightyellow")
label.pack()

rbman = Radiobutton(root, text = "男生", variable = var, value = 1,
	command = printSelection)
rbman.pack()
rbwoman = Radiobutton(root, text = "女生", variable = var, value = 2,
	command = printSelection)
rbwoman.pack()

root.mainloop()

The above setting var variable is an IntVar() object, which is also an integer. The default option is 1, which is equivalent to a boy by default. First, get the value of the current option button by var.get(), then use if to judge whether the selected one is a boy or a girl, and finally use the config() method to set the boy or girl to the text of the label object label, and then display the result of

1.2 Apply the dictionary to the option button

Although the above method of creating option buttons is easy to use, the program will become more complicated when there are more options. At this time, you can consider using a dictionary to store information about option buttons, and then create option buttons by traversing the dictionary.

programming:

from tkinter import *

def printSelection():
	print(cities[var.get()])

root = Tk()
cities = {0: "北京",
		  1: "上海",
		  2: "广州",
		  3: "深圳",
		  }

var = IntVar()
var.set(0)
label = Label(root, text = "请选择最喜欢的城市",
	fg = "blue", bg = "lightyellow").pack()

for val , city in cities.items():
	Radiobutton(root, text = city, 
				variable = var, value = val,
				command = printSelection).pack()

root.mainloop()

1.3 Box option button

Tkinter also provides the concept of box option buttons, you can use the indicatoron parameter in the Radiobutton method and set it to 0

for val , city in cities.items():
	Radiobutton(root, text = city, 
				indicatoron = 0,
				variable = var, value = val,
				command = printSelection).pack()

1.4 Create an option button with an image

You can also replace the option text with an image, and its usage is the same as the label Label

img = PhotoImage(file = '2.png')

for val , city in cities.items():
	Radiobutton(root, text = city, 
				image = img, compound = RIGHT,
				indicatoron = 0,
				variable = var, value = val,
				command = printSelection).pack()

2. Checkbox Checkbutton

Checkboxes can be translated as a checkbox, and its category name in the Widgets control is Checkbutton. A checkbox appears as a box on the screen, and it differs from an option button in that it is a checkbox. When designing a checkbox, the most common way is to let the checkbox exist in text form. Like labels, it is also possible to design checkboxes with images.

During program design, each check box can be designed to be bound with a function (method), and when this option is selected, the related function or method can be automatically executed. In addition, there may be multiple groups of check boxes during program design. At this time, a group of check boxes can be designed to have a related variable, and the variable is bound to this group of check boxes. You can use the Checkbutton() method to create a check box, as follows:

Checkbutton(父对象, options, ……)

The commonly used options parameters are as follows:

activebackground

Background color when the mouse cursor is over the checkbox

activeforeground

The foreground color when the mouse cursor is over the checkbox

bg

The background color of the label background or indicator

bitmap

bitmap image object

borderwidth or bd

The border width defaults to two pixels

command

This function is automatically executed when the user changes an option

cursor

Cursor shape when the mouse cursor is over the checkbox

disabledforeground

Color when inoperable

font

font

height

The number of lines of text in the checkbox, the default is 1 line

highlightbackground

Background color when the checkbox is focused

highlightcolor

The color when the checkbox gets focus

image

image object

justify

When there are multiple lines of text, the alignment of the last line of text

offvalue

Control variable, the default checkbox unselected value is 0, which can be changed by this setting

onvalue

Control variable, the default check box is not selected and the value is 1, which can be changed by this setting

Padx

The default is 1, you can set the interval between the check box and the text

Paddy

The default is 1, you can set the upper and lower spacing of the check box

relief

The default relief=FLAT, which can control the frame of the check box

selectcolor

The color when the checkbox is checked

selectimage

If you set an image checkbox, you can use this to set a different image when the checkbox is selected

state

The default is state=NORMAL. If DISABLED is set, the check box will be displayed in grayscale, indicating that it is temporarily unavailable

text

text next to checkbox

underline

可以设置第几个文字有下划线,从0开始算起,默认是-1,表示无下划线

variable

设置或取得目前选取的复选框,它的值类型通常是IntVar或StringVar

width

复选框的文字有几个字符宽,省略时会自动调整为实际宽度

wraplength

限制每行的文字数,默认是0,表示只有’\n’才会换行

程序设计:

from tkinter import *

def printInfo():
	selection = ''
	for i in checkboxes:
		if checkboxes[i].get() == True:
			selection = selection + cities[i] + "\t"
	print(selection)

root = Tk()
Label(root, text = "请选择想去的城市",
	  fg = "blue", bg = "lightyellow", width = 30).grid()
cities = {0: "北京",
		  1: "上海",
		  2: "广州",
		  3: "深圳",}
checkboxes = {}

for i in range(len(cities)):
	checkboxes[i] = BooleanVar()
	Checkbutton(root, text = cities[i],
				variable = checkboxes[i]).grid(row = i + 1, columnspan = 2)

btn = Button(root, text = "确定", command = printInfo).grid(row = i + 2)
root.mainloop()

上述代码,将checkboxes内容设为BooleanVar对象,经过这样设置后才可以用get()方法取得它的内容。

3.框架Frame

3.1框架的基本概念

这是一个容器控件,当我们设计的GUI程序很复杂时,此时可以考虑将一系列相关的Widget组织在一个框架内,这样可以方便管理。语法如下:

Frame(父对象, options, ……)

其他常用的options参数如下:

bg或background

背景色彩

borderwidth或bd

标签边界宽度,默认是2

cursor

当鼠标光标在框架上时的光标形状

height

框架的高度,单位是像素

highlightcolor

当框架取得焦点时的颜色

highlightbackground

当框架没有取得焦点时的颜色

highlighthickness

当框架取得焦点时的厚度

relief

默认relief=FLAT,可由此控制框架外框

width

框架的宽度,单位是像素,省略时会自动调整为实际宽度

程序设计:

from tkinter import *

root = Tk()

frameUpper = Frame(root, bg = "lightyellow")
frameUpper.pack()
btnRed = Button(frameUpper, text = "红色", fg = "red").pack(side = LEFT)
btnGreen = Button(frameUpper, text = "绿色", fg = "green").pack(side = LEFT)
btnBlue = Button(frameUpper, text = "蓝色", fg = "blue").pack(side = LEFT)

frameLower = Frame(root, bg = "lightblue")
frameLower.pack()
btnPink = Button(frameLower, text = "粉色", fg = "pink").pack(side = LEFT)

root.mainloop()

3.2标签框架LabelFrame

这也是一个容器控件,主要是将一系列相关的Widget组织在一个标签框架内,然后给它一个名称.语法如下:

LabelFrame(父对象, options, ……)

其他常用options和Frame相似

程序设计:

from tkinter import *

root = Tk()
msg = "欢迎进入系统"
img = PhotoImage(file = "2.png")
logo = Label(root, image = img, text = msg, compound = BOTTOM)
logo.pack()

# 以下是LabelFrame标签框架
labFrame = LabelFrame(root, text = "账户登录")
accountL = Label(labFrame, text = "账户")
accountL.grid(row = 0, column = 0)
pwdL = Label(labFrame, text = "密码")
pwdL.grid(row = 1, column = 0)

accountR = Entry(labFrame)
accountR.grid(row = 0, column = 1)
pwdE = Entry(labFrame, show = "*")
pwdE.grid(row = 1, column = 1)
labFrame.pack(padx = 10, pady = 10, ipadx = 5, ipady = 5)

root.mainloop()

3.2.1将标签框架应用于复选框

标签框架的应用范围很广泛,也常应用于将选项按钮或是复选框组织起来

程序设计:

from tkinter import *

def printInfo():
	selection = ""
	for i in checkboxes:
		if checkboxes[i].get() == True:
			selection = selection + cities[i] + "\t"
	print(selection)

root = Tk()
root.geometry("200x200")
# 以下建立标签框架与字典
labFrame = LabelFrame(root, text = "选择最想去的城市")
cities = {0: "北京",
		  1: "上海",
		  2: "广州",
		  3: "深圳",}
checkboxes = {}
for i in range(len(cities)):
	checkboxes[i] = BooleanVar()
	Checkbutton(labFrame, text = cities[i],
				variable = checkboxes[i]).grid(row = i + 1, sticky = W)
labFrame.pack(ipadx = 5, ipady = 5)

btn = Button(root, text = "确定", width = 10, command = printInfo)
btn.pack()

root.mainloop()

3.2.2顶层窗口Toplevel

这个控件的功能类似于Frame,但是这个控件所产生的容器是一个独立的窗口,有自己的标题栏和边框。语法如下:

Toplevel(options, ……)

程序设计:建立一个Toplevel窗口

from tkinter import *

root = Tk()
tl = Toplevel()
Label(tl, text = "这是一个 Toplevel ").pack()

root.mainloop()

Toplevel窗口建立完成后,如果关闭Toplevel窗口,原主窗口仍可以继续使用,但是如果关闭了主窗口,Toplevel窗口将自动关闭

程序设计:使用Toplevel窗口仿真对话框

from tkinter import *
import random

root = Tk()

msgY, msgN, msgE = 1, 2, 3
def MessageBox():
	msgType = random.randint(1,3)
	if msgType == msgY:
		labTxt = "YES"
	elif msgType == msgN:
		labTxt = "NO"
	elif msgType == msgE:
		labTxt = "EXIT"
	tl = Toplevel()
	tl.geometry("50x50")
	tl.title("Mseeage Box")
	Label(tl, text = labTxt).pack(fill = BOTH, expand = True)

btn = Button(root, text = "Click Me", command = MessageBox)
btn.pack()

root.mainloop()

参考资料:《Python GUI设计——tkinter菜鸟编程》洪锦魁著

Guess you like

Origin blog.csdn.net/Lmhark/article/details/128023756