我需要测试文本小部件,或者比较文本行中出现的字符的标签,如果用户按下了所需的按钮,这是在 key_type() 函数中。 为什么调用 event_generate 时没有插入字符?
import tkinter as tkinter
import unittest
from tkinter import *
import main
class MyGUI(tkinter.Frame):
def __init__(self, top, **kw):
super().__init__(top, **kw)
self.button1 = Button(self, text="Играть",command=lambda: main.command())
self.button2 = Button(self, text="Выйти",command=lambda: main.command2())
self.button1.pack()
self.button2.pack()
test_text = "Avd"
self.text_widget = Text(self, height=10, width=100,
padx=20, pady=20, font=("Arial ", 16))
self.text_widget.insert(END, test_text)
self.text_widget.configure(state="disabled")
self.text_widget.tag_config("correct", background="green", foreground="white")
self.text_widget.tag_config("wrong", background="red", foreground="white")
self.text_widget.bind("<KeyPress>", main.key_type)
self.text_widget.focus()
self.text_widget.pack()
class TKinterTestCase(unittest.TestCase):
def setUp(self):
self.top = Toplevel()
self.root2 = Tk()
def tearDown(self):
if self.top:
self.top.destroy()
if self.root2:
self.root2.destroy()
def test_enter1(self):
v = MyGUI(self.top)
v.button2.event_generate('<Button-1>')
self.assertTrue(v.button1.winfo_exists())
def test_enter2(self):
v = MyGUI(self.top)
v.button2.event_generate('<Button-1>')
self.assertTrue(v.button2.winfo_exists())
v.text_widget.focus_set()
v.after(100, lambda: self.root2.event_generate('A'))
self.assertEqual("correct",v.text_widget.tag_names(1.0))
if __name__ == "__main__":
unittest.main()
def key_type(e):
if e.keycode != 16:
global pos, text_widget, b, mistakes, correct_presses
if (test_text[pos] != e.char):
text_widget.tag_add("wrong", str(1) + "." + str(b))
mistakes += 1
if (test_text[pos] == e.char):
text_widget.tag_add("correct", str(1) + "." + str(b))
correct_presses += 1
b += 1
pos += 1
运行测试: '正确' != ()