使用Python在GUI中显示循环周期数

时间:2019-04-24 03:59:28

标签: python-3.6

有没有一种方法可以使用python在GUI中显示循环周期数,我希望脚本在每次迭代后更新周期数(类似于labview中的指示器)。下面的代码在每次迭代后都会打开一个新窗口,我想知道是否有一种无需打开新窗口即​​可更新计数的方法。 ((在这里解决了代码)谢谢。

import tkinter as Toplevel
import time
root = Toplevel.Tk()
for iter in range(10):    
  root.withdraw()
  root = Toplevel.Tk()
  root.geometry('300x200+0+0')
  root.resizable(width=False, height=False)
  root.configure(bg="white")
  root.title("Test" + str(iter))
  label = Toplevel.Label(root, font = ("Arial", 18, "bold"), text="Cycle number:\n" + str(iter), bg="grey", fg="white", width = 20, height = 2)
  label.pack()
  root.update()
  time.sleep(1)

1 个答案:

答案 0 :(得分:1)

如果我很了解您,我认为您首先需要一种面向对象的方法,然后是一种线程管理。

看看这个脚本,您可以设置计数器,然后按“开始”按钮,在名为“获取计数”的标签下面查找。

#!/usr/bin/python3
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import threading
import queue
import time

class MyThread(threading.Thread):

    def __init__(self, queue, count):
        threading.Thread.__init__(self)

        self.queue = queue
        self.check = True
        self.count = count


    def stop(self):
        self.check = False

    def run(self):

        while self.check:
            if self.count <1:
                self.check = False
            else:                
                self.count -= 1
                time.sleep(1)
                self.queue.put(self.count)



class Main(ttk.Frame):
    def __init__(self, parent):
        super().__init__()

        self.parent = parent

        self.queue = queue.Queue()
        self.my_thread = None

        self.spins = tk.IntVar()
        self.count = tk.IntVar()

        self.spins.set(5)

        self.init_ui()

    def init_ui(self):



        f = ttk.Frame()

        ttk.Label(f, text = "Set count").pack()
        tk.Spinbox(f, from_=2, to=20, textvariable= self.spins).pack()

        ttk.Label(f, text = "Get count").pack()
        ttk.Label(f, textvariable = self.count).pack()

        w = ttk.Frame()

        ttk.Button(w, text="Start", command=self.start_count).pack()
        ttk.Button(w, text="Stop", command=self.stop_count).pack()
        ttk.Button(w, text="Close", command=self.on_close).pack()

        f.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
        w.pack(side=tk.RIGHT, fill=tk.BOTH, expand=1)


    def start_count(self):

        if (threading.active_count()!=0):

            self.my_thread = MyThread(self.queue,self.spins.get())
            self.my_thread.start()
            self.on_periodic_call()

    def stop_count(self):
        if self.my_thread is not None:
            if(threading.active_count()!=1):
                self.my_thread.stop()


    def on_periodic_call(self):

        self.on_check_queue()
        if self.my_thread.is_alive():
            self.after(1, self.on_periodic_call)
        else:
            pass

    def on_check_queue(self):
        while self.queue.qsize():
            try:
                self.count.set(self.queue.get(0))
            except queue.Empty:
                pass                    

    def on_close(self):
        if self.my_thread is not None:
            if(threading.active_count()!=1):
                self.my_thread.stop()

        self.parent.on_exit()

class App(tk.Tk):
    """Start here"""

    def __init__(self):
        super().__init__()

        self.protocol("WM_DELETE_WINDOW", self.on_exit)

        self.set_style()
        self.set_title()

        Main(self)

    def set_style(self):
        self.style = ttk.Style()
        #('winnative', 'clam', 'alt', 'default', 'classic', 'vista', 'xpnative')
        self.style.theme_use("clam")


    def set_title(self):
        s = "{0}".format('Simple App')
        self.title(s)

    def on_exit(self):
        """Close all"""
        if messagebox.askokcancel("Simple App", "Do you want to quit?", parent=self):
            self.destroy()               

if __name__ == '__main__':
    app = App()
    app.mainloop()

enter image description here