unistata
unistata

Reputation: 23

Change variable with tkinter button

I got some kind of problem with the structure with my code. I am using Tkinter and building a GUI. My idea is as follows: there is a field that takes the path to a file and when you click Start, Python opens the path and loads the file as a csv. Then it stores the file in a dict with some more information and returns the dict that will be passed around to other functions. However, how can this work? The Button can only run a function but not return something, right?

So I can enter the (partially filled) dict as an argument of this input function, however, it is never returned. My solution until now was to declare it a global, so when it is changed within the function, it is also changed outside. However, now I restructure the code and want to reuse code (since files are imported at several stages in the process). Now, when I want to use the same function again, the global solution seems problematic. Any ideas how I can do this without them? Thanks a lot.

Update1:

class Topclass:
    def changer(x):
        x += 1


class Subclass(Topclass):
    def __init__(self):
        self.b = 2


obb = Subclass()
print(obb.b)
Topclass.changer(obb.b)
print(obb.b)

Upvotes: 2

Views: 112

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36662

@Martineau's advice is correct, there is much to learn from @BryanOakley's Best way to structure a tkinter application's answer.

Using a DataTransfer specialized object is a technique that you can use to pass variables, or data around, with frameworks that do not return values like tkinter, or when you need your data to cross an encapsulation barrier, without tightly coupling the objects involved:

Here is a simple example to illustrate how that works:

class DataTransfer:
    """mutable object that is used to transfer data
    """
    def __init__(self, value: int) -> None:
        self.value = value

    def add_one(self) -> None:
        self.value += 1

    def __str__(self) -> str:
        return f'{self.value}'


class Topclass:
    def changer(x: DataTransfer) -> None:
        x.add_one()


class Subclass(Topclass):
    def __init__(self) -> None:
        self.b = DataTransfer(2)


obb = Subclass()
print(obb.b)
Topclass.changer(obb.b)
print(obb.b)

Upvotes: 1

Related Questions