Как обновить sh страницу в окне Tkinter, когда пользователь нажимает на страницу - PullRequest
0 голосов
/ 30 апреля 2020

В настоящее время я разрабатываю графический интерфейс, используя py tkinter для записи / отображения данных в режиме реального времени. У меня есть файл конфигурации, из которого я получаю настройки, и две страницы, на которых пользователь сможет изменять настройки. Одна из страниц настроек предназначена для добавления информации о работе.

На странице ведения журнала график извлекает данные из информации о задании и настраивает заголовок графика из этой информации, а также некоторые другие вещи.

Когда пользователь нажимает на страницу регистрации, я хотел бы обновить информацию о работе. Я пытался .update () и .after () обновить sh страницу, но она не обновляет sh.

Я новичок в python и новее в tkinter, поэтому мой код не очень хорош, но я прикрепил его для вашей справки.

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import tkinter as tk
from tkinter import ttk
from tkinter import *
import configparser

LARGE_FONT= ("Verdana", 12)
filename_1 = 'x_data_f.txt'
filename_2 = 'y_data_f.txt'

class Pages(tk.Tk):
    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        tk.Tk.wm_title(self, "Graphing Service")
        # tk.wm_attributes("-fullscreen", True)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, PageOne, PageTwo, PageThree):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()


class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text=" Menu ", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button = ttk.Button(self, text="    Job Setup    ", command=lambda: controller.show_frame(PageOne))
        button.pack()

        button2 = ttk.Button(self, text="     Settings      ", command=lambda: controller.show_frame(PageTwo))
        button2.pack()

        button3 = ttk.Button(self, text=" Logging page ", command=lambda: controller.show_frame(PageThree))
        button3.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        config = configparser.ConfigParser()
        config.read('settings.INI')
        # Save job settings entries. 
        def saved_message():
            job_name = job_entry.get()
            max_depth = depth_entry.get()
            hole_number = hole_entry.get()
            save_settings(job_name, max_depth, hole_number)
            tk.Label(self, text="Saved job information").grid(row=6,column=4) 

        label = tk.Label(self, text="Job Setup", font=LARGE_FONT)
        label.grid(row = 0, column = 0)

        button1 = ttk.Button(self, text="Back to Menu", command=lambda: controller.show_frame(StartPage))
        button1.grid(row = 1, column = 0)

        button2 = ttk.Button(self, text="     Settings     ", command=lambda: controller.show_frame(PageTwo))
        button2.grid(row=2, column = 0)

        tk.Label(self, text = "Job Name").grid(row = 1, column = 3) 

        job_entry = tk.Entry(self)
        job_entry.grid(row = 1, column = 4) 

        tk.Label(self, text = "Maximum Depth").grid(row = 2, column = 3) 

        depth_entry = tk.Entry(self)
        depth_entry.grid(row = 2, column = 4) 

        tk.Label(self, text = "Hole Number").grid(row = 3, column = 3) 

        hole_entry = tk.Entry(self)
        hole_entry.grid(row = 3, column = 4) 

        save_butt = ttk.Button(self, text = "Save", state=NORMAL, command=saved_message).grid(row = 5, column = 3, columnspan = 2) 
            # Writing the settings to the file
        def save_settings(job_name, max_depth, hole_number):
            config = configparser.ConfigParser()
            config.read('settings.INI')
            config['JOB SETTINGS']['path'] = '/var/shared/'    # update
            config['JOB SETTINGS']['default_message'] = 'default_message'    # create
            config['JOB SETTINGS']['job_name'] = job_name
            config['JOB SETTINGS']['max_depth'] = max_depth
            config['JOB SETTINGS']['hole_number'] = hole_number
            with open('settings.INI', 'w') as configfile:    # save
                config.write(configfile)
            return

        def get_job_settings():
            config = configparser.ConfigParser()
            config.read('settings.INI')
            path = config['JOB SETTINGS']['path'] 
            default_message = config['JOB SETTINGS']['default_message']
            job_name = config['JOB SETTINGS']['job_name']
            max_depth = config['JOB SETTINGS']['max_depth']
            hole_number = config['JOB SETTINGS']['hole_number']
            return job_name, default_message, path, max_depth, hole_number

        job_name, default_message, path, max_depth, hole_number = get_job_settings()
        job_entry.insert(0, job_name)
        depth_entry.insert(0, max_depth)
        hole_entry.insert(0, hole_number)

class PageTwo(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self,      text="   Settings   ", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = ttk.Button(self,  text=" Back to Menu ", command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = ttk.Button(self,  text="   Job Setup  ", command=lambda: controller.show_frame(PageOne))
        button2.pack()


class PageThree(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        fig = Figure(figsize=(11,7), dpi=100)

        button1 = ttk.Button(self, text=" Back to Menu ", command=lambda: controller.show_frame(StartPage))
        button1.place(x=1, y=0)
        button1.pack(side='left')
        button3 = ttk.Button(self, text="        Start         ", command=self.start,)
        button3.place(x=1, y=5)
        button4 = ttk.Button(self, text="        Finish       ", command=self.finish)
        button4.place(x=1, y=45)
        button2 = ttk.Button(self, text="        Abort        ", command=self.abort)
        button2.pack(side='left')
        button2.place(x=1, y=85)

        def get_job_settings():
            config = configparser.ConfigParser()
            config.read('settings.INI')
            path = config['JOB SETTINGS']['path'] 
            default_message = config['JOB SETTINGS']['default_message']
            job_name = config['JOB SETTINGS']['job_name']
            max_depth = config['JOB SETTINGS']['max_depth']
            hole_number = config['JOB SETTINGS']['hole_number']
            return job_name, default_message, path, max_depth, hole_number

        job_name, default_message, path, max_depth, hole_number = get_job_settings()

        ax = FigureCanvasTkAgg(fig, self)
        ax.draw()
        ax.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
        ax = fig.add_subplot(111)

        voltage_monitored = 0   # Needs to be read from device
        current_monitored = 0   # Needs to be read from device
        probe_setting = 'unknown' # Needs to be read in from the configuration file to know what configurations are been used. 

        with open(filename_1) as x:
            x_data = [float(line.rstrip()) for line in x]
        with open(filename_2) as y:
            y_data = [float(line.rstrip()) for line in y]

        ax.text(0.95, 0.01, 'Voltage: %s\nCurrent: %s\nProbe: %s' %(voltage_monitored, current_monitored, probe_setting),
                verticalalignment='bottom', horizontalalignment='right', transform=ax.transAxes, color='black', fontsize=10)
        ax.set_title('%s: %s' %(job_name, hole_number)) 
        ax.set_xlabel('Gamma, API') 
        ax.set_ylabel('Depth, m')
        ax.xaxis.set_label_position('top')
        ax.xaxis.tick_top()

        ax.set_xlim(xmin=0, xmax=80)
        ax.set_ylim(ymin=0, ymax=(int(max_depth) + 10))      
        ax.invert_yaxis()
        ax.plot(y_data, x_data)

        # toolbar = NavigationToolbar2Tk(ax, self)
        # toolbar.update()
        # ax._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

    def abort(self):
        # end the logging and clear the logs 
        print("Clear logs.")

    def start(self):
        # This needs to activate the logger and start 
        Tk.update(self)

        print("Starting logger.")

    def finish(self):
        # Needs to log all the data into an excel file. Will create a function for that with all preset values
        # the same as the example template in excel has given for excel. 
        print("Saving data.")

app = Pages()
app.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...