Search code examples
python-3.xtkintertkinter-canvaslabel-encoding

Display list of text in tkinter


I want to display the result of my label encoding in tkinter like I display it using print function in python.

from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()
df["REPORT_FAMILY"] = le.fit_transform(df["REPORT_FAMILY"])
print("Mapping: ")
for i, item in enumerate(le.classes_):
    print(item, "-->", i)

This code produce a results like this:

Mapping: 
ADELBERT SC3000 --> 0
ADELBERT SC3020 --> 1
ALAR --> 2
ALTER EGO SC460 --> 3
ALTER EGO SCV360 --> 4
ARYA --> 5
BEACHCOMBER --> 6

How I do the same in tkinter?I use the following code but received an error. My target is to display the encoded REPORT_FAMILY column to the respective category in the REPORT_FAMILY.

import tkinter as tk 
#creating the window
window = tk.Tk()
window.title("FPY+ Prediction")

canvas1 = tk.Canvas(window, width = 500, height = 300)
canvas1.pack()

t = tk.Text(window)
for i, item in enumerate(le.classes_):
    t.insert(item, "-->", i)
t.pack()

window.mainloop()

I receive the following error:

---------------------------------------------------------------------------
TclError                                  Traceback (most recent call last)
<ipython-input-30-6c09ea2a9048> in <module>
     11 canvas1.create_window(200, 300)
     12 for i, item in enumerate(le.classes_):
---> 13     t.insert(item, "-->", i)
     14 t.pack()
     15 

~\Anaconda3\lib\tkinter\__init__.py in insert(self, index, chars, *args)
   3270         """Insert CHARS before the characters at INDEX. An additional
   3271         tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
-> 3272         self.tk.call((self._w, 'insert', index, chars) + args)
   3273     def mark_gravity(self, markName, direction=None):
   3274         """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).

TclError: bad text index "ADELBERT SC3000"

Solution

  • The first argument to the insert method needs to be an index. The most common are "insert" for inserting at the insertion cursor, and "end" for inserting at the end.

    After the index and the item to be inserted, the next argument is interpreted as a list of tags. So, if you want "-->" and i to be part of the text that is inserted, you need to include it as part of the second argument.

    You also need to add a newline.

    t.insert(item, f"{item} --> {i}\n")