0
from tkinter import *
from tkinter import ttk
import tkinter as tk
import time
class __MENU__(tk.Tk):
    def insert_(self):
        while True:
            self.text_box.insert('end','hi\n')
            time.sleep(1)
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry('700x350')
        self.title('AUTO-TDS')
        frame=ttk.Frame(self)
        self.text_box=Text(frame,height=13,width=30,wrap='word')
        #self.text_box.insert('end','Auto Trao Đổi Sub v1\n')
        self.text_box.pack(side=LEFT,expand=True)
        sb=ttk.Scrollbar(frame)
        sb.pack(side=RIGHT, fill=BOTH)
        self.text_box.config(yscrollcommand=sb.set)
        sb.config(command=self.text_box.yview)
        frame.pack(expand=True)
        self.bnt=ttk.Button(self,text='start',command=self.insert_).place(x=500,y=300)
        
if __name__=='__main__':
    __MENU__().mainloop()

when i press start my interface is unresponsive , I want to use while loop to print continuously, how to do?

1
  • 1
    Use .after() instead of while loop and time.sleep(). Commented Jul 30, 2021 at 4:01

1 Answer 1

2

Loops mess with mainloop. Use .after(). Your while loop will keep going on for ever because condition is always True.

def insert_(self):
      self.text_box.insert('end','hi\n')
      self.after(1000,self.insert_)

If you want to use while loop., use threading module.

from tkinter import *
from tkinter import ttk
import tkinter as tk
import time,threading
class __MENU__(tk.Tk):
    def insert_(self):
        while True:
            self.text_box.insert('end','hi\n')
            time.sleep(1)
    def insert_text(self):
        x=threading.Thread(target=self.insert_)
        x.daemon = True
        x.start()
    def __init__(self):
        tk.Tk.__init__(self)
        ....
        self.bnt=ttk.Button(self,text='start',command=self.insert_text).place(x=500,y=300)
       
if __name__=='__main__':
    __MENU__().mainloop()
Sign up to request clarification or add additional context in comments.

6 Comments

I am required to use while . loop
is there any other way?
def insert_(self): self.text_box.insert('end','hi\n') self.after(1000,self.insert_) def start(self): while True: self.insert_
@NguyễnPhúKhương, check my updated answer
@NguyễnPhúKhương: why are you required to use a while loop? That's almost always the wrong solution in a GUI program.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.