Tkinter, удалите лишние строки, если значения удалены из файла CSV - PullRequest
1 голос
/ 10 февраля 2020

Я пытаюсь построить производственное расписание GUI в Tkinter. Отдельный фрагмент кода получит доступ к моему производственному расписанию и вставит данные в файл csv. Поскольку задания выполняются в планировщике, список в данных CSV становится меньше. По мере добавления новых заданий список в данных CSV становится длиннее. Проблема заключается в том, что когда список становится длиннее, он вносит определенное количество записей. Метка не ссылается на sh, чтобы показывать меньше записей, когда записи удаляются из файла CSV.

Если я выключил tk-интерфейс и снова открыл его, он показывает правильную информацию, поэтому я знаю, что Мне нужно обновить sh метку, однако использование label.destroy () этого не делает. Я попытался сделать csv_label глобальной меткой, чтобы она могла быть непосредственно ссылкой в ​​моей оконной функции refre sh, чтобы она могла уничтожить этот точный экземпляр метки, но, похоже, это не сработало. Я правильно использую уничтожить?

# import the required modules
import tkinter as tk
import datetime
import time
import threading
import csv

#create the tk interface window
window = tk.Tk()
window.title("Test")
window.geometry('1024x768+-7+0')

#create a clock label to show current time
clock_label = tk.Label(window)
clock_label.grid(column=1, row=0)

#clock function to get current time
def clock():
    time = datetime.datetime.now().strftime("Time: %I:%M:%S %p")
    clock_label.config(text=time)
    window.after(1000, clock)

#csv function which gets info from test.csv and pastes it into the label, situated on the window
def paste_csv():
    with open("test.csv", newline="") as file:
        reader = csv.reader(file)
        r = 0
        for col in reader:
            c = 0
            for row in col:
                # i've added some styling
                global csv_label
                csv_label = tk.Label(window, width=30, height=2, \
                        text=row, relief=tk.RIDGE, bg="white")
                csv_label.grid(row=r, column=c)
                c += 1
            r += 1

#attempt at destroying the label from the window
def refresh_window():
    csv_label.destroy()

#at every second, update the csv data on the window
def paste(delay):
  next_time = time.time() + delay
  while True:
    time.sleep(max(1, next_time - time.time()))
    try:
        paste_csv()
    except:
        print("tick1")

#at every 5 seconds, refresh the data on the window to reflect changes
def refresh(delay):
  next_time = time.time() + delay
  while True:
    time.sleep(max(4, next_time - time.time()))
    try:
        refresh_window()
    except:
        print("tick2")

#Thread initiations
threading.Thread(target=lambda: paste(1)).start()
threading.Thread(target=lambda: refresh(5)).start()

#autodisplay clock and csv data on startup
clock()
paste_csv()

#main window loop
window.mainloop()

1 Ответ

2 голосов
/ 11 февраля 2020

Вам не нужно использовать темы для вставки меток и refre sh. Используйте after() достаточно. Чтобы удалить избыточные метки, необходимо иметь список, содержащий созданные метки, и использовать этот список для удаления существующих меток перед созданием новых меток:

# import the required modules
import tkinter as tk
import csv
import datetime

# hold the csv labels
csv_label_list = []

#create the tk interface window
window = tk.Tk()
window.title("Test")
window.geometry('1024x768+0+0')

#create a clock label to show current time
clock_label = tk.Label(window)
clock_label.grid(column=1, row=0)

#clock function to update current time
def clock():
    time = datetime.datetime.now().strftime("Time: %I:%M:%S %p")
    clock_label.config(text=time)
    window.after(1000, clock)

#csv function which gets info from test.csv and pastes it into the label, situated on the window
def paste_csv():
    with open("test.csv", newline="") as file:
        # remove existing labels
        for lbl in csv_label_list:
            lbl.destroy()
        csv_label_list.clear()
        # create new labels
        reader = csv.reader(file)
        r = 0
        for col in reader:
            c = 0
            for row in col:
                # i've added some styling
                csv_label = tk.Label(window, width=30, height=2,
                                     text=row, relief=tk.RIDGE, bg="white")
                csv_label.grid(row=r, column=c)
                csv_label_list.append(csv_label)
                c += 1
            r += 1
    # update every 5 seconds
    window.after(5000, paste_csv)

#autodisplay clock and csv data on startup
clock()
paste_csv()

#main window loop
window.mainloop()

* Обратите внимание, что если их больше, чем один столбец в первой строке файла CSV, часы будут покрыты новой меткой.

...