Home > database >  tkinter code after mainloop() not being executed after closing window
tkinter code after mainloop() not being executed after closing window

Time:05-04

I need help using tkinter in python. I want to use a while loop inside my class so that it keeps printing in the terminal the content of an entry (box1). But the problem is that if I put a loop in my class the entry wont even be created because the root.mainloop() is after my while loop.

The program:

from tkinter import *
from tkinter import ttk
import tkinter as tk

class root(Tk):
    def __init__(self):
        super(root, self).__init__()
        
        self.minsize(500,400)
        self.configure(bg='#121213')

        self.createEntry()


    def createEntry(self):
        self.name1 = StringVar()
        self.box1 = ttk.Entry(self, width=2, textvariable = self.name1, font="Calibri 15")
        self.box1.place(x=128, y=31)
        while True:
            print(self.name1.get())


        
root=root()
root.mainloop()

If I put the loop after the root.mainloop() it won't start printing the contents of name1 as long as the tkinter file is open. So it will print only the final version of name1 in a loop: The Code:

from tkinter import *
from tkinter import ttk
import tkinter as tk

class root(Tk):
    def __init__(self):
        super(root, self).__init__()
        
        self.minsize(500,400)
        self.configure(bg='#121213')

        self.createEntry()


    def createEntry(self):
        self.name1 = StringVar()
        self.box1 = ttk.Entry(self, width=2, textvariable = self.name1, font="Calibri 15")
        self.box1.place(x=128, y=31)
        while True:
            print(self.name1.get())


        
root=root()
root.mainloop()
while True:
    print(root.name1.get())

Video of my problem

Does anyone have any solution?

CodePudding user response:

How about a solution that does not put constant drain on the processing power? If you add a callback to StringVar, you can trigger a function every time the variable is changed, and only then. Infinite loops don't work very well with UI applications, as in order to avoid stopping the control flow of the app you have to use things like async, threading etc.

    def createEntry(self):
        self.name1 = StringVar()
        self.name1.trace_add("write", lambda name, index, mode: print(self.name1.get()))
        self.box1 = ttk.Entry(self, width=2, textvariable = self.name1, font="Calibri 15")
        self.box1.place(x=128, y=31)

This piece of code will make given lambda function trigger every time something is written to name1 variable.

  • Related