python-3.x - 如何使用 tkinter.Label 更改文本颜色
问题描述
我正在尝试构建我的第一个 GUI 程序并想知道谁来更改标签文本颜色?例如,将其更改为“红色”
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="what's my favorite video?", pady=10, padx=10, font=10,)
label.pack()
click_here = tk.Button(root, text="click here to find out", padx = 10, pady = 5)
click_here.pack()
root.mainloop()
非常感谢 :-)
解决方案
您可以使用可选参数bg
和fg
(请注意,您可能需要highlightbackground
在 MacOS 系统上使用不同的选项,如本答案中所述) - 我认为这是 MacOS 上的一个已知问题tk.Button
。
import tkinter as tk
root = tk.Tk()
# bg is to change background, fg is to change foreground (technically the text color)
label = tk.Label(root, text="what's my favorite video?",
bg='#fff', fg='#f00', pady=10, padx=10, font=10) # You can use use color names instead of color codes.
label.pack()
click_here = tk.Button(root, text="click here to find out",
bg='#000', fg='#ff0', padx = 10, pady = 5)
click_here.pack()
root.mainloop()
我添加这个作为答案的唯一原因是因为我在一个类似的问题上为 SO 上的某个人写的最后一个答案只是因为他们使用的是 Mac 而不起作用。如果你在 Windows 机器上,你没问题。
推荐阅读
- c++ - 获取模板中数组最小值的函数
- android - 推送通知因 curl 失败
- javascript - 如何在 JS 中制作一个按钮数组?以及如何设置随机图像?
- reactjs - 与 redux 执行 async 并一起反应悬念
- python - 按最频繁的字段对 namedtupled 列表进行排序
- excel - PowerBI:从混合文件夹文件中导入数据
- kotlin - 如何调用入队回调?
- ios - 保存的 VPN 配置需要更新吗?
- tensorflow - ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)
- css - top/bottom 和 left/right: auto 如何与绝对定位一起工作?