Marek Marek - 3 months ago 8
Python Question

Python - how to get value from a text field in another module

I've written a simple program with a tkinter GUI. The entire code is in one big module and I'd like to split it into two or three modules to separate the logic from the GUI.
This is the example code:

main.py:



import gui
inst1 = gui.guitest()


gui.py:



import tkinter, defs

class guitest:
def __init__(self):
win1 = tkinter.Tk()
self.field1 = tkinter.Text(win1)
self.field1.grid(column = 0, row = 0)
self.but1 = tkinter.Button(win1, text='click',
command=defs.getVar)
self.but1.grid(column = 1, row = 0)
win1.mainloop()


defs.py:



def getVar():
captured = str(field1.get(1.0))


I can't get getVar to work; I'd like it to get the value from the Text field, but after trying different solutions all I get are Name or Attribute Errors.
Is there any possibility to make it work that way? Or maybe my idea is completely wrong? If it is, then please let me know how to do it. I wonder if there are more problems with this code.

BPL BPL
Answer

Alright, let's start from the beginning, here's a working example of your code:

import tkinter


class guitest:

    def __init__(self):
        win1 = tkinter.Tk()
        self.field1 = tkinter.Text(win1)
        self.field1.grid(column=0, row=0)
        self.but1 = tkinter.Button(win1, text='click', command=self.getVar)
        self.but1.grid(column=1, row=0)
        win1.mainloop()

    def getVar(self):
        captured = str(self.field1.get("1.0", tkinter.END))
        print captured

inst1 = guitest()

Now, before breaking down that piece of code, you should ask yourself if the reason you want to is strong enough. In case your answer is affirmative (think it twice) one possible way to do it would be this:


# main.py
import gui
inst1 = gui.guitest()

# gui.py
import tkinter
import defs

class guitest:

    def __init__(self):
        win1 = tkinter.Tk()
        self.field1 = tkinter.Text(win1)
        self.field1.grid(column=0, row=0)
        self.but1 = tkinter.Button(win1, text='click', command=self.getVar)
        self.but1.grid(column=1, row=0)
        win1.mainloop()

    def getVar(self):
        defs.getVar(self)

# defs.py
import tkinter


def getVar(guitest_inst):
    captured = str(guitest_inst.field1.get("1.0", tkinter.END))
    print captured

But again, think twice before breaking down widgets like this... just saying :)

Comments