簡體   English   中英

按鈕和無限循環(GUI,python)

[英]Buttons and infinite while loop (GUI, python)

我編寫了一個 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)

此外,我有一個 function 實時分析 output 文本文件,即它在通過無限循環寫入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 按鈕時開始分析 function 並結束分析 function,即在按下 END 按鈕時跳出while循環。 我的想法是放置一個標志,它初始化while循環,當按下 END 按鈕時,標志值會發生變化,你會跳出 while 循環。 然后只需將分析 function 放在開始測量 function 中。 有點像這樣:

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)

所以這是我天真的新手想法。 但問題是當我點擊開始按鈕時,結束按鈕被禁用,因為我正在進入無限循環,我猜我無法停止這個過程。 我知道這有點含糊,但也許有人對如何處理這個問題有想法? 我也想過使用線程,但無法使其工作。 我不知道這是否是一個好方法。

每次使用 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM