Python Forum
[Tkinter] Defining a self made module's function to interact with the main .py variables?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Defining a self made module's function to interact with the main .py variables?
#1
Question 
I'm using Tkinter. (self learner)
My goal is to display the function's output in the main .py text widget.
How can I make the function send the output to the text box in the main .py file?

** UPDATE 2 **
[Image: GaLRq.jpg]
[Image: KBjss.jpg]

** UPDATE **
i've updated the code and now I get that:

[Image: mwsrw.jpg]
[Image: ghjkb.jpg]

[Image: 2Sxck.jpg]

Main .py:

import tkinter as tk
import multiprocessing as mp
import os
import testping
import sys


class GUI(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry("860x600")
        self.title("GUI Project")

        menu = tk.Frame(self, relief="solid")
        container = tk.Frame(self, relief="solid")

        menu.pack(side="left", fill="y")
        container.pack(side="right", fill="y", expand=True)

        menu.grid_rowconfigure(0, weight=1)
        container.grid_rowconfigure(0, weight=1)
        container.grid_rowconfigure(1, weight=1)
        container.grid_rowconfigure(2, weight=1)
        container.grid_rowconfigure(3, weight=1)
        container.grid_rowconfigure(4, weight=1)
        container.grid_rowconfigure(5, weight=1)
        container.grid_rowconfigure(6, weight=1)
        container.grid_columnconfigure(0, weight=1)
        container.grid_columnconfigure(1, weight=2)
        container.grid_columnconfigure(2, weight=2)
        container.grid_columnconfigure(3, weight=2)
        container.grid_columnconfigure(4, weight=2)
        container.grid_columnconfigure(5, weight=2)
        container.grid_columnconfigure(6, weight=2)

        self.frames = ["Menu", "TestPing", "FutureFeature", "FutureFeature2", "FutureFeature3"]

        self.frames[0] = Menu(parent=menu, controller=self)
        self.frames[1] = TestPing(parent=container, controller=self)
        self.frames[2] = FutureFeature(parent=container, controller=self)
        self.frames[3] = FutureFeature2(parent=container, controller=self)
        self.frames[4] = FutureFeature3(parent=container, controller=self)

        self.frames[0].grid(row=0, column=0, sticky="nsew")
        self.frames[1].grid(row=0, column=0, sticky="nsew")
        self.frames[2].grid(row=0, column=0, sticky="nsew")
        self.frames[3].grid(row=0, column=0, sticky="nsew")
        self.frames[4].grid(row=0, column=0, sticky="nsew")

        self.show_frame(1)

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        print(frame)
        frame.tkraise()
        frame.grid(row=0, column=0, sticky="nsew")


class Menu(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        ping_test_button = tk.Button(self, text="Ping Test", bg="skyblue1", pady=30,
                                     command=lambda: controller.show_frame(1))
        future_feature1_button = tk.Button(self, text="FutureFeature", bg="dark violet", pady=30,
                                           command=lambda: controller.show_frame(2))
        future_feature2_button = tk.Button(self, text="FutureFeature2", bg="pale goldenrod", pady=30,
                                           command=lambda: controller.show_frame(3))
        future_feature3_button = tk.Button(self, text="FutureFeature3", bg="green", pady=30,
                                           command=lambda: controller.show_frame(4))
        app_exit = tk.Button(self, text="Quit", bg="gray40", pady=30,
                             command=lambda: self.terminate())

        ping_test_button.pack(fill="both", expand=True)
        future_feature1_button.pack(fill="both", expand=True)
        future_feature2_button.pack(fill="both", expand=True)
        future_feature3_button.pack(fill="both", expand=True)
        app_exit.pack(fill="both", expand=True)

    def terminate(self):

        while True:
            path = fr'c:/users/{os.getlogin()}/desktop/Gui-Skeleton'

            try:
                os.rmdir(path)
                exit()
            except OSError as err:
                print(f"Error Deleting tmp folder! {err}")
                exit()


class TestPing(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent, bg="skyblue1")
        self.controller = controller


        self.clear_file = tk.BooleanVar()
        self.clear_file.set(False)

        self.url_label = tk.Label(self, text="Enter URL : ", padx=7, pady=5, bg="skyblue1")
        self.url_input_box = tk.Entry(self)

        self.file_name_label = tk.Label(self, text="Enter Filename: ", bg="skyblue1")
        self.file_name_input_box = tk.Entry(self)

        self.clear_file_label = tk.Label(self, text="Clear File?", padx=5, pady=5, bg="skyblue1")

        self.clear_file_radio_yes = tk.Radiobutton(self, text="yes", value=True, var=self.clear_file, bg="skyblue1",
                                                   command=lambda: self.callback(self.clear_file.get()))
        self.clear_file_radio_no = tk.Radiobutton(self, text="no", value=False, var=self.clear_file, bg="skyblue1",
                                                  command=lambda: self.callback(self.clear_file.get()))
        self.submit_button = tk.Button(self, text="Submit", width=10, height=1,
                                       command=lambda: self.condition(self.url_input_box.get(),
                                                                      self.clear_file.get(),
                                                                      self.file_name_input_box.get()))
        self.clear_fields_button = tk.Button(self, text="Clear Fields", width=10,
                                             command=lambda: self.clear_boxes(self.url_input_box,
                                                                              self.file_name_input_box))

        self.text_input = tk.StringVar()
        self.text_window = tk.Text(self, height=100, width=500, bg="gray")
        self.clear_window_button = tk.Button(self, text="Clear Window", width=10,
                                             command=lambda: self.clean_window())

        self.grid_columnconfigure(0, minsize=50, weight=0)
        self.grid_columnconfigure(1, minsize=20, weight=2)
        self.grid_columnconfigure(2, minsize=50, weight=3)
        self.grid_columnconfigure(3, minsize=20, weight=2)
        self.grid_rowconfigure(0, minsize=50, weight=0)
        self.grid_rowconfigure(1, minsize=20, weight=0)
        self.grid_rowconfigure(2, minsize=30, weight=0)
        self.grid_rowconfigure(3, minsize=10, weight=0)
        self.grid_rowconfigure(4, minsize=10, weight=0)
        self.grid_rowconfigure(5, minsize=10, weight=0)

        self.url_label.grid(row=0, column=0, sticky="w")
        self.url_input_box.grid(row=0, column=1, sticky="w")
        self.file_name_label.grid(row=1, column=0, sticky="w")
        self.file_name_input_box.grid(row=1, column=1, sticky="w")
        self.clear_file_label.grid(row=0, column=1, sticky="n")
        self.clear_file_radio_yes.grid(row=1, column=1)
        self.clear_file_radio_no.grid(row=2, column=1)
        self.submit_button.grid(row=3, column=1, sticky="se")
        self.clear_fields_button.grid(row=3, column=1, sticky="sw")
        self.text_window.grid(row=7, column=1, rowspan=3, sticky="we")
        self.clear_window_button.grid(row=8, column=0)

    def clear_boxes(self, url_input, filename):
        url_input.delete(0, "end")
        filename.delete(0, "end")

    def callback(self, clear):
        print(f'Clear file = {clear}')  # Debugging Mode - check Radio box Var.

    def condition(self, host, clear, filename):

        print(clear, filename)  # Debugging - Input Validation

        if clear is True and filename == '':
            self.handler_clr_yes_fn_no(host)
        elif clear is False and filename == '':
            self.handler_clr_no_fn_no(host)
        elif clear is True and filename != '':
            self.handler_clr_yes_fn_yes(host, filenameInputBox)
        elif clear is False and filename != '':
            self.handler_clr_no_fn_yes(host, filenameInputBox)

    def handler_clr_yes_fn_no(self, host):

        startprocs = []
        lastprocs = []

        proc1 = mp.Process(name="Clear + No Filename + WriteFile",
                           target=testping.clr_yes_fn_no_writefile, args=(host,))
        proc2 = mp.Process(name="Clear + No Filename + PrintOutput",
                           target=testping.clr_yes_fn_no_print_output, args=(host,))
        proc3 = mp.Process(name="Clear + No Filename + Generate PrintOutput to GUI",
                           target=testping.clr_yes_fn_no_print_to_gui, args=(host,))
        proc4 = mp.Process(name="Remove first line + Write new default file",
                           target=testping.delete_default_lines)

        startprocs.append(proc1)
        startprocs.append(proc2)
        startprocs.append(proc3)

        lastprocs.append(proc4)

        for s in startprocs:
            s.start()

        for s2 in startprocs:
            s2.join()

        for l in lastprocs:
            l.start()

    def handler_clr_no_fn_no(self, host):

        procs = []
        nextprocs = []

        proc1 = mp.Process(name="Append to default file",
                           target=testping.clr_no_fn_no_writefile, args=(host,))
        proc2 = mp.Process(name="Print Output", target=testping.clr_no_fn_no_printoutput, args=(host,))

        procs.append(proc1)
        procs.append(proc2)

        for proc in procs:
            proc.start()
        for proc in procs:
            proc.join()

        for p in nextprocs:
            p.start()

    def handler_clr_yes_fn_yes(self, host, filenameInputBox):

        procs = []
        nextprocs = []

        proc1 = mp.Process(name="Clear file + userFilename + Write to file",
                           target=testping.clr_yes_fn_yes_writefile, args=(host, filenameInputBox,))
        proc2 = mp.Process(name="Clear file + user filename + Print output",
                           target=testping.clr_yes_fn_yes_printoutput, args=(host,))
        proc3 = mp.Process(name="Remove Empty Lines from user filename",
                           target=testping.delete_userfile_lines, args=(filenameInputBox,))

        procs.append(proc1)
        procs.append(proc2)
        nextprocs.append(proc3)

        for proc in procs:
            proc.start()

        for p in procs:
            p.join()

        for np in nextprocs:
            np.start()

    def handler_clr_no_fn_yes(self, host, filenameInputBox):

        procs = []

        proc1 = mp.Process(name="Keep File + Userfilename + Append to Userfile",
                           target=testping.clr_no_fn_yes_writefile, args=(host, filenameInputBox,))
        proc2 = mp.Process(name="Keep File + Userfilename + Print Output",
                           target=testping.clr_no_fn_yes_printoutput, args=(host,))

        procs.append(proc1)
        procs.append(proc2)

        for p in procs:
            p.start()

        for p2 in procs:
            p2.join()


class FutureFeature(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg="mediumpurple1")
        self.controller = controller  # can be used to run self.controller.show_frame[]


class FutureFeature2(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg="light goldenrod")
        self.controller = controller


class FutureFeature3(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg="green")
        self.controller = controller


def check_path():
    path = fr'c:/users/{os.getlogin()}/desktop/Gui-Skeleton'

    try:

        if os.path.isdir(path):
            pass

        else:
            os.mkdir(path)
            pass

    except OSError as err:
        print(f"[!] Operation failed! {err}")


if __name__ == "__main__":

    check_path()
    app = GUI()
    app.mainloop()
Module testping.py:

import subprocess as sub
import multiprocessing as mp
import time
import os
import sys
import tkinter as tk

clear_file = False
host = ""
filename = ""
text_box = tk.StringVar()
old_sys = sys.stdout


def delete_default_lines():
    time.sleep(1.5)
    print(f'\nCurrent Proccess: {mp.current_process().name} + {mp.current_process().pid}')
    file = fr'c:/users/{os.getlogin()}/Desktop/Gui-Skeleton/default-tmp.txt'
    newfile = fr'c:/users/{os.getlogin()}/Desktop/default.txt'

    with open(file, 'r') as inp, open(newfile, 'w+') as out:
        for line in inp:
            if not line.isspace():
                out.write(line.lstrip())
                out.write('')
        inp.close()
        out.close()
    os.remove(file)


def delete_userfile_lines(filename):
    time.sleep(1.5)
    print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}')
    file = fr'c:/users/{os.getlogin()}/Desktop/Gui-Skeleton/{filename}-tmp.txt'
    newfile = fr'c:/users/{os.getlogin()}/Desktop/{filename}.txt'

    with open(file, 'r+') as inp, open(newfile, 'w+') as out:
        for line in inp:
            if not line.isspace():
                out.write(line.lstrip())
                out.write('')
        inp.close()
        out.close()
    os.remove(file)


def clr_yes_fn_no_print_output(host):
    print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')
    with sub.Popen(["ping", "-n", "4", f'{host}'], stdout=sub.PIPE,
                   bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
        for line in p.stdout:
            print(line, end=' ')


def clr_yes_fn_no_print_to_gui(host):
    print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')

    cmd = ["ping", "-n", "4", f'{host}']
    proc = sub.Popen(cmd, stdout=sub.PIPE, shell=True, stderr=sub.STDOUT)
    for stdout_line in proc.stdout:
        print(stdout_line.decode(), end='')
        # yield stdout_line
    proc.stdout.close()
    # return_code = proc.wait()
    # if return_code:
    #     raise sub.CalledProcessError(return_code, cmd)


def clr_yes_fn_no_writefile(host):
    print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')
    file = fr'c:/users/{os.getlogin()}/Desktop/Gui-Skeleton/default-tmp.txt'
    ping = sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE)
    with open(file, 'w+') as output:
        data = output.read()
        for line in ping.stdout.readlines():
            data += str(line.decode())
        ping.stdout.close()
        output.seek(0)
        output.write(data.lstrip())


def clr_no_fn_no_printoutput(host):
    print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')
    with sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE,
                   bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
        for line in p.stdout:
            print(line, end=' ')


def clr_no_fn_no_writefile(host):
    print(f'Current Proccess: {mp.current_process().name} + {mp.current_process().pid}\n')
    with open(fr'c:/users/{os.getlogin()}/Desktop/default.txt', 'a') as output:
        sub.call(["ping", "-n", '4', f'{host}'], stdout=output)


def clr_yes_fn_yes_printoutput(host):
    with sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE,
                   bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
        for line in p.stdout:
            print(line, end=' ')


def clr_yes_fn_yes_writefile(host, filename):
    file = fr'c:/users/{os.getlogin()}/Desktop/Gui-Skeleton/{filename}-tmp.txt'
    with open(file, 'w') as output:
        sub.call(["ping", "-n", '4', f'{host}'], stdout=output)


def clr_no_fn_yes_printoutput(host):
    with sub.Popen(["ping", "-n", '4', f'{host}'], stdout=sub.PIPE,
                   bufsize=1, universal_newlines=True, stderr=sub.STDOUT) as p:
        for line in p.stdout:
            print(line, end=' ')


def clr_no_fn_yes_writefile(host, filename):
    with open(fr'c:/users/{os.getlogin()}/Desktop/{filename}.txt', 'a') as output:
        sub.call(["ping", "-n", '4', f'{host}'], stdout=output)
GUI:

[Image: Hv15d.jpg]
Reply


Messages In This Thread
Defining a self made module's function to interact with the main .py variables? - by Gilush - Jun-07-2020, 12:23 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I run an interface I made using PyQt5 and a Map program I made using Tkinter bki 6 1,294 Nov-09-2023, 11:12 PM
Last Post: bki
  [PyQt] Managing variables accross a multiple module GUI Oolongtea 18 10,981 Sep-19-2019, 12:13 PM
Last Post: Oolongtea
  “main thread is not in main loop” in Tkinter Long_r 1 24,430 Jun-26-2019, 11:00 PM
Last Post: metulburr
  [Tkinter] Bringing function out of class into main loop zukochew 1 2,707 Jul-30-2018, 06:43 PM
Last Post: Axel_Erfurt
  GTK main window calling a main window DennisT 4 6,921 Oct-19-2016, 09:36 PM
Last Post: DennisT

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020