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()

当我按下开始时,我的界面没有响应,我想使用while循环连续打印,怎么办?

4

1 回答 1

2

循环与mainloop. 使用.after(). 您的 while 循环将永远持续下去,因为条件始终为真。

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

如果要使用 while 循环,请使用threading模块。

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()
于 2021-07-30T04:01:44.400 回答