python利用Radiobutton和Checkbutton控件实现选择字体和颜色
时间: 2024-05-10 09:16:45 浏览: 6
下面是一个简单的 Python 程序,利用 Radiobutton 和 Checkbutton 控件实现选择字体和颜色的功能:
```python
from tkinter import *
from tkinter import font
from tkinter.colorchooser import askcolor
class FontChooser:
def __init__(self, master):
self.master = master
master.title("字体和颜色选择器")
# 创建字体选择器
self.font_label = Label(master, text="选择字体:")
self.font_label.pack()
self.font_choice = StringVar()
self.font_choice.set("Arial")
self.font_1 = Radiobutton(master, text="Arial", variable=self.font_choice, value="Arial")
self.font_1.pack(anchor=W)
self.font_2 = Radiobutton(master, text="Times New Roman", variable=self.font_choice, value="Times New Roman")
self.font_2.pack(anchor=W)
self.font_3 = Radiobutton(master, text="Courier New", variable=self.font_choice, value="Courier New")
self.font_3.pack(anchor=W)
# 创建颜色选择器
self.color_label = Label(master, text="选择颜色:")
self.color_label.pack()
self.color_choice = StringVar()
self.color_choice.set("#000000")
self.color_button = Button(master, text="选择颜色", command=self.choose_color)
self.color_button.pack()
# 创建文本框
self.text_label = Label(master, text="输入文本:")
self.text_label.pack()
self.text = Text(master)
self.text.pack()
# 创建按钮
self.ok_button = Button(master, text="确定", command=self.apply_font)
self.ok_button.pack()
def choose_color(self):
color = askcolor()
if color:
self.color_choice.set(color[1])
def apply_font(self):
chosen_font = font.Font(family=self.font_choice.get(), size=12)
self.text.config(font=chosen_font, fg=self.color_choice.get())
root = Tk()
my_gui = FontChooser(root)
root.mainloop()
```
在这个程序中,我们首先创建了一个 `FontChooser` 类,它包含字体选择器、颜色选择器、文本框和一个确定按钮。字体选择器使用 `Radiobutton` 控件,我们可以选择 Arial、Times New Roman 或 Courier New 三种字体中的一种。颜色选择器使用 `Checkbutton` 控件,当我们点击选择颜色按钮时,会弹出一个颜色选择对话框,我们可以从中选择颜色。最后,当我们点击确定按钮时,程序会根据我们的选择来应用字体和颜色到文本框中。
如果你希望在程序中添加更多的字体或颜色选项,只需要在 `FontChooser` 类中添加相应的 `Radiobutton` 或 `Checkbutton` 控件即可。