Tkinter |使用 ttk.Entry 小部件向输入文本添加样式
Tkinter 是一个广泛用于创建 GUI 应用程序的 GUI(图形用户界面)模块。它与Python本身一起提供。
条目小部件用于从用户那里获取条目。它可以创建如下 -
entry = ttk.Entry(master, option = value, ...)
代码 #1:创建 Entry 小部件并从用户那里获取输入(仅获取字符串数据)。
# importing tkinter
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import askyesno
# creating root
root = Tk()
# specifying geometry
root.geometry('200x100')
# This is used to take input from user
# and show it in Entry Widget.
# Whatever data that we get from keyboard
# will be treated as string.
input_text = StringVar()
entry1 = ttk.Entry(root, textvariable = input_text, justify = CENTER)
# focus_force is used to take focus
# as soon as application starts
entry1.focus_force()
entry1.pack(side = TOP, ipadx = 30, ipady = 6)
save = ttk.Button(root, text = 'Save', command = lambda : askyesno(
'Confirm', 'Do you want to save?'))
save.pack(side = TOP, pady = 10)
root.mainloop()
输出:
在上面的输出中,只要你运行代码,就会出现一个 Tkinter 窗口,并且 Entry 小部件已经聚焦,这意味着我们不必将焦点放在 Entry 区域。
当我们按下 Button 时会出现一条确认信息,说明是否要保存文本(它不会保存文本,它仅用于显示 Button 的功能)。代码 #2:在 Entry 小部件中为输入的文本添加样式。
# importing tkinter
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import askyesno
# creating root
root = Tk()
root.geometry('200x100')
input_text = StringVar()
# This class is used to add styling
# to any widget which are available
style = ttk.Style()
style.configure('TEntry', foreground = 'green')
entry1 = ttk.Entry(root, textvariable = input_text, justify = CENTER,
font = ('courier', 15, 'bold'))
entry1.focus_force()
entry1.pack(side = TOP, ipadx = 30, ipady = 10)
save = ttk.Button(root, text = 'Save', command = lambda : askyesno(
'Confirm', 'Do you want to save?'))
save.pack(side = TOP, pady = 10)
root.mainloop()
输出:
在上面的输出中,您可能会注意到字体颜色发生了变化,字体系列发生了变化,文本的大小比正常大,并且文本以粗体书写。这是因为我们正在为输入文本添加样式。