首页 > 解决方案 > 让表情符号在 tkinter 中工作,并使其可被代码覆盖,但在运行时不能被最终用户覆盖

问题描述

我需要在 tkinter 中创建一个存储表情符号的字段,但是当有人按下按钮时,该表情符号会被覆盖。我无法在 tkinter 中使用表情符号,我不知道如何覆盖它。

import tkinter as tk

self.option4 = tk.Button(self, width=10)
self.option4["text"] = "no"
self.option4["command"] = self.wrong
self.option4.pack(side="top")

corecalc = ""

self.answercheck = tk.Text(self, height=1, width=5)
self.answercheck.pack()
self.answercheck.insert(tk.END, corecalc)

self.QUIT = tk.Button(self, text="Quit", fg="red", command=root.destroy)
        self.QUIT.pack(side="bottom")

def correct(self):
  corecalc = "✅"

def wrong(self):
  corecalc = "❌"

字段中的预期输出并在按下按钮时变为❌。还有比文本框更好的方法可以使字段固定而不是最终用户可编辑。

错误:_tkinter.TclError: character U+1f532 is above the range (U+0000-U+FFFF) allowed by Tcl

标签: pythonpython-3.xtkinterunicodeemoji

解决方案


您可以使用任何 tkinter 小部件来显示您需要的字符 - 表情符号或其他 -Text如果您想显示单个字符,小部件是一个糟糕的选择,尽管可能。

如果您真的想使用Text,您可以通过将其stateKey 设置为“disabled”(与默认的“normal”相反)将其更改为不可编辑:

self.answercheck = tk.Text(self, height=1, width=5, state="disabled")

文本框将要求您在插入新文本之前删除以前的文本,tkinter.Label如果您希望仅对字符进行编程更改,则可以简单地使用小部件:

import tkinter as tk

w = tk.Tk()
display = tk.Label(w, text="□")
display.pack()

def correct():
  display["text"] = "✅"

def wrong():
  display["text"] = "❌"


button = tk.Button(w, text="no", command=wrong)
button.pack()
button = tk.Button(w, text="yes", command=correct)
button.pack()
tkinter.mainloop()

(在我在这里的构建中 - Linux fedora 上的 Python 3.7,tkinter 无法直接处理您的角色,因为它的代码点高于 \uffff)


推荐阅读