【问题标题】:Buttons and infinite while loop (GUI, python)按钮和无限循环(GUI,python)
【发布时间】:2020-11-04 23:17:06
【问题描述】:

我编写了一个 GUI 来控制测量设备及其数据采集。

代码的简化草图如下所示:

def start_measurement():
    #creates text file (say "test.txt") and write lines with data to it continuously

def stop_measurement():
    #stops the acquisition process. The text file is saved.

startButton = Button(root, text = "start", command = start_measurement)
endButton = Button(root, text = "end", command = stop_measurement)

此外,我还有一个实时分析输出文本文件的函数,即它在通过无限while 循环写入文本文件时连续读取文本文件:

def analyze():
    file_position = 0
    while True: 
        with open ("test.txt", 'r') as f:
            f.seek(file_position)
              
            for line in f:
                  #readlines an do stuff
              
            fileposition = f.tell()

现在我想在按下 START 按钮时启动分析功能并在按下 END 按钮时结束分析功能,即跳出while 循环。我的想法是放置一个标志,它初始化while 循环,当按下 END 按钮时,标志值会发生变化,你会跳出 while 循环。然后只需将分析功能放在开始测量功能中即可。 有点像这样:

def analyze():

    global initialize
    initialize = True

    file_position = 0
    
    while True: 
        if initialize:
             with open ("test.txt", 'r') as f:
                    f.seek(file_position)
              
                    for line in f:
                       #readlines an do stuff
              
                    fileposition = f.tell()
        else: break



def start_measurement():
    #creates text file (say "test.txt") and writes lines with data to it
    analyze()

def stop_measurement():
    #stops the acquisition process
    initialize = False

startButton = Button(root, text = "start", command = start_measurement)
endButton = Button(root, text = "end", command = stop_measurement)

所以这是我幼稚的新手想法。但问题是当我点击开始按钮时,结束按钮被禁用,因为我正在进入无限循环,我猜我无法停止这个过程。我知道这有点含糊,但也许有人对如何处理这个问题有想法?我也想过使用线程,但无法使其工作。我不知道这是否是一个好方法。

【问题讨论】:

  • 你应该创建一个运行无限循环的线程。

标签: python user-interface tkinter


【解决方案1】:

每次你使用 gui 并且你创建一个循环或一个需要很长时间的进程时,除非你使用 gui 的机制或线程,否则 gui 会冻结,在 tkinter 中你可以使用 kivy 中的“after”方法,你使用 Clock。

您可以将它与线程结合使用,但是对于线程,您必须知道自己在做什么,否则您的 gui 会出现异常。

所以在这里我为你做了一个基本的 tkinter 工作示例,它使用 tkinter "after" 方法来避免界面冻结。

我使用你提到的标志,所以它类似于你想要的。

from tkinter import Tk, mainloop
from tkinter.ttk import Button, Label, Frame


counter = 0
stop_counter = False

def start(label):
    global counter
    global stop_counter
    counter += 1
    label.config(text=counter)
    if not stop_counter:
        label.after(1000, start, label)
    else:
        stop_counter = False

def stop():
    global stop_counter
    stop_counter = True

win = Tk()

lbl = Label(win, text='0', font=("Lucida Grande", 20))
lbl.pack()
frm = Frame()
frm.pack()
btn = Button(frm, text='Start Counter', command=lambda label=lbl: start(label))
btn.pack(side='left')
btn = Button(frm, text='Stop Counter', command=stop)
btn.pack(side='right')


mainloop()

【讨论】:

    猜你喜欢
    • 2011-10-28
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2023-01-31
    • 2012-04-10
    相关资源
    最近更新 更多