Skip to content
Advertisement

How to print Dictionary’s items in Tkinter Text Widget?

I have created a program, which allows user to enter usernames of individuals and assign specific number (points) to a particular name.

As a result, all data is stored in dictionary like that:

{'Username': 0, 'Username2': 0, .... and so on} 

When User click on “Results” Button, new window appear and I can see this dictionary printed in terminal. However, now I want to print the data of this dictionary in Text box in new Tkinter window. I tried to do so, but nothing appears in text box.

Or I should use label widget to do so?

How to solve this problem?

I’m thinking that I should change something here, but I don’t know what exactly

class resultPage(ttk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ttk.Frame.__init__(self, parent)
        self.userEntry()

    def userEntry(self):
        preInd = Label(self, text="Points of Individuals:", font="Arial 20")
        preInd.grid(row=0, column=0, pady=10, padx=10)
        self.inputInd = Text(self, height=10, width=15)
        self.inputInd.grid(row=1, column=0)

        for i in IndividPoints:
            self.inputInd.insert(END, i + 'n')


if __name__ == '__main__':
    Individuals = []
    IndividPoints = {}
    app = CollegeApp()
    app.geometry("800x500")
    app.resizable(False, False)
    app.title('Points Counter')
    app.mainloop()


Here is the working part of my code:

from tkinter import *
from tkinter import messagebox
import tkinter.ttk as ttk


class CollegeApp(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.container = ttk.Frame(self)
        self.container.pack(side="top", fill="both", expand=True)
        self.frames = {}
        for F in (IndividPage, counterPage, resultPage):
            frame = F(self.container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(IndividPage)
        self.lift()

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

    def show_list_frame(self):
        list_frame = counterPage(self.container, self)
        list_frame.grid(row=0, column=0, sticky="nsew")
        list_frame.tkraise()


class IndividPage(ttk.Frame):

    def __init__(self, parent, controller):
        self.controller = controller
        ttk.Frame.__init__(self, parent)
        self.userEntry()

    def userEntry(self):
        headingTest = Label(self, text="Enter your UserName:", font="Arial 20")
        headingTest.grid(row=0, column=0, pady=5, padx=5)

        self.usernameEnter = Entry(self, width=40)
        self.usernameEnter.grid(row=0, column=1, padx=5, pady=5)

        confirmBtn = Button(self, text="Confirm User", font="Arial 16",
                            command=self.confirm)

        confirmBtn.config(height=4, width=12)
        confirmBtn.grid(row=2, column=2, sticky=E, padx=45, pady=360)

    def confirm(self):
        if self.add_to_indivList():
            pass

    def add_to_indivList(self):
        user = self.usernameEnter.get()
        if len(user) == 0:
            messagebox.showwarning(title='No user', message='Please enter a username!')
            return
        if self.usernameEnter.get():
            self.controller.show_frame(counterPage)

        if user in Individuals:
            messagebox.showwarning(title='In team', message=f'{user} is already in Individuals list!')

        Individuals.append(user)
        processedInd = list(dict.fromkeys(Individuals))
        self.controller.show_list_frame()
        print(processedInd)
        print(len(Individuals))


class counterPage(ttk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ttk.Frame.__init__(self, parent)
        self.userEntry()

    def confirm2(self):
        if self.get_points():
            pass

    def userEntry(self):

        self.indList = Listbox(self)
        self.indList.config(height=13, width=15)
        self.indList.grid(row=0, column=0, padx=10, pady=20)
        for user in Individuals:
            self.indList.insert(END, user)

        backBtn = Button(self, text="BACK", font="Arial 16", height=2, width=6,
                         command=lambda: self.controller.show_frame(IndividPage))
        backBtn.grid(row=1, column=0, sticky=W, pady=10, padx=10)

        testBtn = Button(self, text="Create Entry Boxes", command=self.indivSelect)
        testBtn.grid(row=2, column=0, sticky=W)

        resultBtn = Button(self, text="Results", height=2, width=6,
                           command=lambda: self.confirm2())
        resultBtn.grid(row=3, column=0, sticky=W)

        self.indList.bind("<<ListboxSelect>>", self.onSelect)

    def onSelect(self, event):
        selection = event.widget.curselection()
        if selection:
            print(f"User selected item {selection[0]}")
            print("Click on 'Create Entry Boxes' button to enter points for selected user")
        else:
            print("User deselected")

    def indivSelect(self):
        self.ptEnter = []
        for col_num in range(1, 6):
            self.temp = Entry(self, width=2)
            self.temp.grid(row=0, column=col_num)
            self.ptEnter.append(self.temp)

    def get_points(self):
        def Ind_get_if_int(value):
            if value.isnumeric():
                return int(value)
            return 0

        pointsCalcuator = []
        for self.temp in self.ptEnter:
            pointsCalcuator.append(Ind_get_if_int(self.temp.get()))

        selection = self.indList.curselection()
        IndName = self.indList.get(selection[0])
        IndividPoints[IndName] = sum(pointsCalcuator)

        print(IndividPoints)

        self.controller.show_frame(resultPage)


class resultPage(ttk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ttk.Frame.__init__(self, parent)
        self.userEntry()

    def userEntry(self):
        preInd = Label(self, text="Points of Individuals:", font="Arial 20")
        preInd.grid(row=0, column=0, pady=10, padx=10)
        self.inputInd = Text(self, height=10, width=15)
        self.inputInd.grid(row=1, column=0)

        for i in IndividPoints:
            self.inputInd.insert(END, i + 'n')


if __name__ == '__main__':
    Individuals = []
    IndividPoints = {}
    app = CollegeApp()
    app.geometry("800x500")
    app.resizable(False, False)
    app.title('Points Counter')
    app.mainloop()



Advertisement

Answer

Does this fix Your issue (changes to the code You said wasn’t working):

import tkinter.ttk as ttk
from tkinter import Tk, END, Label, Text


class resultPage(ttk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        ttk.Frame.__init__(self, parent)
        self.userEntry()

    def userEntry(self):
        preInd = Label(self, text="Points of Individuals:", font="Arial 20")
        preInd.grid(row=0, column=0, pady=10, padx=10)
        self.inputInd = Text(self, height=10, width=15)
        self.inputInd.grid(row=1, column=0)

        for i in IndividPoints:
            self.inputInd.insert(END, i + 'n')


if __name__ == '__main__':
    Individuals = []
    IndividPoints = {'Username': 0, 'Username2': 0}
    app = Tk()
    app.geometry("800x500")
    app.resizable(False, False)
    app.title('Points Counter')
    resultPage(app, None).pack()
    app.mainloop()

First of I added values to IndividPoints and second I actually packed the frame so that is on screen (You will have to adjust that accordingly but this example works)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement