📜  Python Tkinter |创建 LabelFrame 并向其添加小部件

📅  最后修改于: 2022-05-13 01:54:36.477000             🧑  作者: Mango

Python Tkinter |创建 LabelFrame 并向其添加小部件

Tkinter 是一个Python模块,用于创建 GUI(图形用户界面)应用程序。它是一个广泛使用的模块,随Python一起提供。它由各种类型的小部件组成,可用于使 GUI 更加用户友好和有吸引力,并且可以增加功能。

LabelFrame 可以按如下方式创建:

-> import tkinter
-> create root
-> create LabelFrame as child of root
label_frame = ttk.LabelFrame(parent, value = options, ...)

代码 #1:创建 LabelFrame 并向其添加消息。

# Import only those methods
# which are mentioned below, this way of
# importing methods is efficient
from tkinter import Tk, mainloop, LEFT, TOP
from tkinter.ttk import *
  
# Creating tkinter window with fixed geometry
root = Tk()
root.geometry('250x150')
  
# This will create a LabelFrame
label_frame = LabelFrame(root, text = 'This is Label Frame')
label_frame.pack(expand = 'yes', fill = 'both')
  
label1 = Label(label_frame, text = '1. This is a Label.')
label1.place(x = 0, y = 5)
  
label2 = Label(label_frame, text = '2. This is another Label.')
label2.place(x = 0, y = 35)
  
label3 = Label(label_frame,
           text = '3. We can add multiple\n    widgets in it.')
  
label3.place(x = 0, y = 65)
  
# This creates an infinite loop which generally
# waits for any interrupt (like keyboard or
# mouse) to terminate
mainloop()

输出:
代码 #2:在 LabelFrame 中添加 Button 和 CheckButton 小部件。

# Import only those methods
# which are mentioned below, this way of
# importing methods is efficient
from tkinter import Tk, mainloop, LEFT, TOP
from tkinter.ttk import *
  
# Creating tkinter window with fixed geometry
root = Tk()
root.geometry('250x150')
  
# This will create a LabelFrame
label_frame = LabelFrame(root, text = 'This is Label Frame')
label_frame.pack(expand = 'yes', fill = 'both')
  
# Buttons
btn1 = Button(label_frame, text = 'Button 1')
btn1.place(x = 30, y = 10)
btn2 = Button(label_frame, text = 'Button 2')
btn2.place(x = 130, y = 10)
  
# Checkbuttons
chkbtn1 = Checkbutton(label_frame, text = 'Checkbutton 1')
chkbtn1.place(x = 30, y = 50)
chkbtn2 = Checkbutton(label_frame, text = 'Checkbutton 2')
chkbtn2.place(x = 30, y = 80)
  
# This creates infinite loop which generally
# waits for any interrupt (like keyboard or
# mouse) to terminate
mainloop()

输出:

注意:也可以在另一个 LabelFrame 中添加另一个LabelFrame 并且可以像我们对其他小部件的样式一样对任何LabelFrame进行样式设置。