You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Tkinter输入框输入文本与输出框展示文本的颜色

Tkinter猜数游戏文本颜色修改方案

1. 修改输入框正在输入的文本颜色

Tkinter的Text组件可通过fg参数直接指定默认文本颜色,你在创建输入框inputtxt时增加该参数即可,示例:

inputtxt = Text(root, height=10,
                width=35,
                bg="gray",
                fg="white") # 这里设置输入文本为白色,可替换为你需要的颜色值

2. 修改输出框打印结果的文本颜色

如果需要给不同状态的输出设置不同颜色(比如正确提示用绿色、错误提示用红色),需要用到Text组件的标签(tag)功能,步骤如下:

  • 创建Output组件后,注册两个标签分别绑定对应的颜色
  • 插入文本时指定使用的标签即可

修改后完整可运行代码

from tkinter import *
import random
a = random.randint(1,10)
print(a)
root = Tk()
root.geometry("500x500")
root.title(" peleg's random number")

wrongtxt = "Wrong answer the number was, {}".format(a)
righttxt=  "Correct the number was {}".format(a)


def Take_input():
    INPUT = inputtxt.get("1.0", "end-1c",)
    print(INPUT)
    # 每次输出前清空上一次的结果,不需要可以删掉这行
    Output.delete("1.0", END)
    if (INPUT == format(a)):
        # 插入时指定right标签,对应绿色
        Output.insert(END, righttxt, "right")
    else:
        # 插入时指定wrong标签,对应红色
        Output.insert(END, wrongtxt, "wrong")


l = Label(text="pick a number between 1-10")
# 输入框增加fg参数设置输入文本颜色
inputtxt = Text(root, height=10,
                width=35,
                bg="gray",
                fg="white")

Output = Text(root, height=10,
              width=35,
              bg="black")
# 注册两个标签分别设置不同颜色
Output.tag_config("right", foreground="green")
Output.tag_config("wrong", foreground="red")

Display = Button(root, height=2,
                 bg="black",
                 width=20,
                 text="Show",
                 command=lambda: Take_input())

l.pack()
inputtxt.pack()
Display.pack()
Output.pack()

mainloop()

内容的提问来源于stack exchange,提问作者peleg siegel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:24:00