Variable not sharing same value between two different functions Python

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 648 Views - Last Post: 30 September 2018 - 09:35 AM Rate Topic: -----

#1 albert9120   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 31-August 18

Variable not sharing same value between two different functions Python

Posted 31 August 2018 - 01:51 PM

I would need to create a Python 2.7 script using Tkinter which should do the following:

When clicking on the "Create the NWs" button in a window -> I should see a field and a "Add network" button near the field. If I have more than one field to introduce, then I should press on the "Add network" button and see another field afterwards to fill in. If I have one or more than one field completed => should write in the file according to the "for" described in the define function. If I do not have any field completed, the file should not be created

The Tkinter part is doing what it should, but the code is not writing it correctly in the file. Here is the relevant part inside of a class where the problem is:

class Networks(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.create_widgets()

    def create_widgets(self):
        label = tk.Label(self, text="Insert the name of the networks")
        start_button = tk.Button(self, text="Return to start page", command=lambda: master.switch_frame(StartPage))
        new_network_button = tk.Button(self, text="Add network", command=self.add_network)
        new_network_button.bind("<Return>", self.add_network)
        new_network_button.grid(row=len(self.master.networks), column=3, padx=4, pady=6, sticky="W")
        next_button=tk.Button(self, text="Next", command=self.networks)
        next_button.grid(row=1500, column=5,padx=4, pady=6, sticky="W")
        label.pack(side="top", fill="x", pady=10)
        start_button.pack()
        new_network_button.pack()
        next_button.pack()
        for index, network in enumerate(self.master.networks):
            self.render_network_field(network, index)

    def add_network(self):
        self.master.networks.append({'variable': tk.StringVar(self.master)})
        self.master.switch_frame(Networks)

    def render_network_field(self, network, index):
        entry_field = tk.Entry(self, textvariable=network['variable'])
        entry_field.grid(row=index, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
        entry_field.pack()
        global s
        s=entry_field.get()  
        print hex(id(s)) 

    def networks(self):
        with open("/home/dante/networks.yml", "w") as f:
             f.write("--- #" + "\n")
             f.write("networks:" + "\n")
             print hex(id(s))
             for ent in s:
                 if ent:
                    f.write("- { cloud: cloud1, network: "+str(ent)+ " }"+ "\n")


Now, the file is written just like this, like "s" is not even existing:

--- # 
networks:


I have printed the hex id in "render_network_field" and in "networks" functions and it is seems that the "s" IDs are different. I thought that the "s" has the same value in both functions. That's the reason that I am getting nothing written in the file.

Any idea how I can correct this?

P.S. Please note that I am quite new to programming.

Is This A Good Question/Topic? 0
  • +

Replies To: Variable not sharing same value between two different functions Python

#2 ndc85430   User is offline

  • I think you'll find it's "Dr"
  • member icon

Reputation: 895
  • View blog
  • Posts: 3,603
  • Joined: 13-June 14

Re: Variable not sharing same value between two different functions Python

Posted 31 August 2018 - 11:11 PM

For a start, s isn't defined anywhere in the networks method. I then see above in your render_network_field method that you're using global. Generally, globals are to be avoided because they can be modified from anywhere and that makes it harder to debug problems when they occur. Having said that, if you need some data (or state) that needs to be accessed by methods of your class and (only methods of your class), why isn't it just an attribute in that class?

Also, you should give your variables meaningful names where possible. s tells the reader of the code nothing about what that variable is for and using good names helps people (you included!) to read and understand the code.
Was This Post Helpful? 0
  • +
  • -

#3 albert9120   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 31-August 18

Re: Variable not sharing same value between two different functions Python

Posted 01 September 2018 - 12:16 PM

@ndc85430: Thank you for your reply. I have updated the code according to your suggestion, but I am still not getting the values in the loop. Any other idea how we can fix?

Here is the whole code added:

import Tkinter as tk
import ttk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.networks = []
        self.switch_frame(StartPage)
    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()


class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        start_label = tk.Label(self, text="This is the start page")
        networks_button = tk.Button(self, text="Create the Openstack deployment and run it", command=lambda: master.switch_frame(Networks))
        script_button = tk.Button(self, text="Run the Script", command=lambda: master.switch_frame(ScriptPage))
        start_label.pack(side="top", fill="x", pady=10)
        networks_button.pack()
        script_button.pack()

class Networks(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.create_widgets()
        self.entries=''
    def create_widgets(self):
        label = tk.Label(self, text="Insert the name of the networks")
        start_button = tk.Button(self, text="Return to start page", command=lambda: master.switch_frame(StartPage))
        new_network_button = tk.Button(self, text="Add network", command=self.add_network)
        new_network_button.bind("<Return>", self.add_network)
        new_network_button.grid(row=len(self.master.networks), column=3, padx=4, pady=6, sticky="W")
        next_button=tk.Button(self, text="Next", command=self.networks)
        next_button.grid(row=1500, column=5,padx=4, pady=6, sticky="W")
        label.pack(side="top", fill="x", pady=10)
        start_button.pack()
        new_network_button.pack()
        next_button.pack()
        for index, network in enumerate(self.master.networks):
            self.render_network_field(network, index)

    def add_network(self):
        self.master.networks.append({'variable': tk.StringVar(self.master)})
        self.master.switch_frame(Networks)

    def render_network_field(self, network, index):
        entry_field = tk.Entry(self, textvariable=network['variable'])
        entry_field.grid(row=index, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
        entry_field.pack()
        self.entries=entry_field.get()  

    def networks(self):
        with open("/home/dante/networks.yml", "w") as f:
             f.write("--- #" + "\n")
             f.write("networks:" + "\n")
             for ent in self.entries:
                 if ent:
                    f.write("- { cloud: cloud1, network: "+str(ent)+ " }"+ "\n")
 
class ScriptPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        page_2_label = tk.Label(self, text="This is page two")
        start_button = tk.Button(self, text="Return to start page",command=lambda: master.switch_frame(StartPage))
        page_2_label.pack(side="top", fill="x", pady=10)
        start_button.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Was This Post Helpful? 0
  • +
  • -

#4 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 463
  • View blog
  • Posts: 1,468
  • Joined: 27-December 13

Re: Variable not sharing same value between two different functions Python

Posted 01 September 2018 - 11:28 PM

@albert9120: Your problem is not very well described.

Do you get an error message?
Can you describe the expected vs. actual output/performance?
Is the problem still related to the title subject, or is it a new problem?

Try to be as specific as possible; it will help us to help you...
Was This Post Helpful? 0
  • +
  • -

#5 albert9120   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 31-August 18

Re: Variable not sharing same value between two different functions Python

Posted 02 September 2018 - 12:32 AM

@DK3250: Thank you for your reply.

The plan of the whole script is the following:

When I run the Python script and clicking on the "Create the NWs" button in the window -> I should see a field and a "Add network" button near the entry field. If I have more than one field to introduce, then I should press on the "Add network" button and see another field afterwards to fill in. Until here, everything works fine. If I have one or more than one field completed => should write in the file according to the "for" described in the define function. If I do not have any field completed, the file should not be created.

With the code that it is attached in my previous comment, everything is working well until the file is created. I do not get any error message, but, right after I am filling with the desired input in the entry fields and clicking "Next", I am getting always just this part in the output file, like the entry fields where not even filled in:

--- #
networks:


From this behavior, I am drawing the conclusion that the "entries" values are not taken from "networks" function into "render_network_field" function. That's why I am saying that the variable value is not shared between these two networks.

If you need some other details, please let me know. I have attached also the whole code in my previous comment to have a better view of it.

Many thanks,
Albert
Was This Post Helpful? 0
  • +
  • -

#6 albert9120   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 31-August 18

Re: Variable not sharing same value between two different functions Python

Posted 02 September 2018 - 12:40 AM

between these two functions*
Was This Post Helpful? 0
  • +
  • -

#7 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 463
  • View blog
  • Posts: 1,468
  • Joined: 27-December 13

Re: Variable not sharing same value between two different functions Python

Posted 02 September 2018 - 02:53 AM

Hm, you assign 'self.entries' in the method (function) 'render_network_field()', line 57.

If the method 'networks()' starting line 59 is executed before 'render_network_field()', then 'self.entries' holds the initialization value (an empty string).

I did not run your code (I currently don't have Python 2 installed), my comments builds on code scrutinizing only.
Was This Post Helpful? 0
  • +
  • -

#8 ndc85430   User is offline

  • I think you'll find it's "Dr"
  • member icon

Reputation: 895
  • View blog
  • Posts: 3,603
  • Joined: 13-June 14

Re: Variable not sharing same value between two different functions Python

Posted 02 September 2018 - 03:05 AM

I initially thought that too, but render_network_field is called in create_widgets, which is called by the class' __init__ method. I guess something's wrong with how that field is being populated in the first place (though I've not tried the code either).
Was This Post Helpful? 0
  • +
  • -

#9 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 463
  • View blog
  • Posts: 1,468
  • Joined: 27-December 13

Re: Variable not sharing same value between two different functions Python

Posted 02 September 2018 - 03:05 AM

Oh, just noticed:
In line 57 you do: self.entries=entry_field.get()
So in each pass of the function the value of self.entries is overwritten!
You probably want self.entries to be a list (or other container) from where you can iterate (line 63)

EDIT:
Explanation of current behavior:
When clicking on 'Next' the self.entries holds an empty string (because that's what's in the field) and this empty string is what you try later to iterate over.

This post has been edited by DK3250: 02 September 2018 - 04:38 AM

Was This Post Helpful? 0
  • +
  • -

#10 albert9120   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 31-August 18

Re: Variable not sharing same value between two different functions Python

Posted 02 September 2018 - 07:53 AM

@DK3250, @ndc85430: I have tried what you have suggested by declaring the self.entries as a list before defining the "Networks" class, but the file is written in the same way. This correction is what you have suggested? Is any other way to modify it?
Here is what I have tried:

import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.networks = []
        self.entries = []
        self.switch_frame(StartPage)
    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()


class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        start_label = tk.Label(self, text="This is the start page")
        networks_button = tk.Button(self, text="Create the Openstack deployment and run it", command=lambda: master.switch_frame(Networks))
        script_button = tk.Button(self, text="Run the Script", command=lambda: master.switch_frame(ScriptPage))
        start_label.pack(side="top", fill="x", pady=10)
        networks_button.pack()
        script_button.pack()

class Networks(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.create_widgets()
    def create_widgets(self):
        label = tk.Label(self, text="Insert the name of the networks")
        start_button = tk.Button(self, text="Return to start page", command=lambda: master.switch_frame(StartPage))
        new_network_button = tk.Button(self, text="Add network", command=self.add_network)
        new_network_button.bind("<Return>", self.add_network)
        new_network_button.grid(row=len(self.master.networks), column=3, padx=4, pady=6, sticky="W")
        next_button=tk.Button(self, text="Next", command=self.networks)
        next_button.grid(row=1500, column=5,padx=4, pady=6, sticky="W")
        label.pack(side="top", fill="x", pady=10)
        start_button.pack()
        new_network_button.pack()
        next_button.pack()
        for index, network in enumerate(self.master.networks):
            self.render_network_field(network, index)

    def add_network(self):
        self.master.networks.append({'variable': tk.StringVar(self.master)})
        self.master.switch_frame(Networks)

    def render_network_field(self, network, index):
        entry_field = tk.Entry(self, textvariable=network['variable'])
        entry_field.grid(row=index, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
        entry_field.pack()
        self.entries=entry_field.get()  

    def networks(self):
        with open("/home/dante/networks.yml", "w") as f:
             f.write("--- #" + "\n")
             f.write("networks:" + "\n")
             for ent in self.entries:
                 if ent:
                    f.write("- { cloud: cloud1, network: "+str(ent)+ " }"+ "\n")
 
class ScriptPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        page_2_label = tk.Label(self, text="This is page two")
        start_button = tk.Button(self, text="Return to start page",command=lambda: master.switch_frame(StartPage))
        page_2_label.pack(side="top", fill="x", pady=10)
        start_button.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()


I think that if you are changing "import Tkinter as tk" into "import tkinter as tk", the code should work in Python 3, as well.

Many thanks,
Albert
Was This Post Helpful? 0
  • +
  • -

#11 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 463
  • View blog
  • Posts: 1,468
  • Joined: 27-December 13

Re: Variable not sharing same value between two different functions Python

Posted 02 September 2018 - 09:00 AM

In line 56 you need to add to the list. To do this use the append() method; rough example:
>>> my_list = [1, 2]
>>> my_list.append(3)
>>> my_list
[1, 2, 3]
>>> 

Was This Post Helpful? 0
  • +
  • -

#12 albert9120   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 31-August 18

Re: Variable not sharing same value between two different functions Python

Posted 02 September 2018 - 10:28 AM

@DK3250: Thanks a lot. It worked like this:

import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.networks = []
        self.switch_frame(StartPage)
    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()


class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        start_label = tk.Label(self, text="This is the start page")
        networks_button = tk.Button(self, text="Create NWs", command=lambda: master.switch_frame(Networks))
        script_button = tk.Button(self, text="Run the Script", command=lambda: master.switch_frame(ScriptPage))
        start_label.pack(side="top", fill="x", pady=10)
        networks_button.pack()
        script_button.pack()

class Networks(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.entries=[]
        self.create_widgets()

    def create_widgets(self):
        label = tk.Label(self, text="Insert the name of the networks")
        start_button = tk.Button(self, text="Return to start page", command=lambda: master.switch_frame(StartPage))
        new_network_button = tk.Button(self, text="Add network", command=self.add_network)
        new_network_button.bind("<Return>", self.add_network)
        new_network_button.grid(row=len(self.master.networks), column=3, padx=4, pady=6, sticky="W")
        next_button=tk.Button(self, text="Next", command=self.networks)
        next_button.grid(row=1500, column=5,padx=4, pady=6, sticky="W")
        label.pack(side="top", fill="x", pady=10)
        start_button.pack()
        new_network_button.pack()
        next_button.pack()
        for index, network in enumerate(self.master.networks):
            self.render_network_field(network, index)

    def add_network(self):
        self.master.networks.append({'variable': tk.StringVar(self.master)})
        self.master.switch_frame(Networks)

    def render_network_field(self, network, index):
        nw_entry_field = tk.Entry(self, textvariable=network['variable'])
        nw_entry_field.grid(row=index, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
        nw_entry_field.pack()
        self.entries.append(network['variable'])

    def networks(self):
        with open("/home/dante/networks.yml", "w") as f:
             f.write("--- #" + "\n")
             f.write("networks:" + "\n")
             for ent in self.entries:
                 value=ent.get()
                 if value:
                    f.write("- { cloud: cloud1, network: "+value+ " }"+ "\n")
 
class ScriptPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        page_2_label = tk.Label(self, text="This is page two")
        start_button = tk.Button(self, text="Return to start page",command=lambda: master.switch_frame(StartPage))
        page_2_label.pack(side="top", fill="x", pady=10)
        start_button.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()


Now, since I have advanced a little bit, I would need to attach the proper cloud for each network, since not all networks have the same "cloud1". Hence, I have added a new entry field for cloud to take the value introduced by the user, but I would need somehow to zip the values.

I have tried something like this, but it seems that I haven't zipped them correctly:

import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.networks = []
        self.switch_frame(StartPage)
    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()


class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        start_label = tk.Label(self, text="This is the start page")
        networks_button = tk.Button(self, text="Create the Openstack deployment and run it", command=lambda: master.switch_frame(Networks))
        script_button = tk.Button(self, text="Run the Script", command=lambda: master.switch_frame(ScriptPage))
        start_label.pack(side="top", fill="x", pady=10)
        networks_button.pack()
        script_button.pack()

class Networks(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.entries=[]
        self.cloudentries=[]
        self.create_widgets()

    def create_widgets(self):
        label = tk.Label(self, text="Insert the name of the networks")
        start_button = tk.Button(self, text="Return to start page", command=lambda: master.switch_frame(StartPage))
        new_network_button = tk.Button(self, text="Add network", command=self.add_network)
        new_network_button.bind("<Return>", self.add_network)
        new_network_button.grid(row=len(self.master.networks), column=3, padx=4, pady=6, sticky="W")
        next_button=tk.Button(self, text="Next", command=self.networks)
        next_button.grid(row=1500, column=5,padx=4, pady=6, sticky="W")
        label.pack(side="top", fill="x", pady=10)
        start_button.pack()
        new_network_button.pack()
        next_button.pack()
        for index, cloud, network in enumerate(self.master.networks):
            self.render_network_field(network, cloud, index)

    def add_network(self):
        self.master.networks.append({'variable': tk.StringVar(self.master)})
        self.master.networks.append({'cloudvariable': tk.StringVar(self.master)})
        self.master.switch_frame(Networks)

    def render_network_field(self, network, cloud, index):
        nw_entry_field = tk.Entry(self, textvariable=network['variable'])
        nw_entry_field.grid(row=index, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
        nw_entry_field.pack()
        cloud_entry_field = tk.Entry(self, textvariable=network['cloudvariable'])
        cloud_entry_field.grid(row=index, column=1, columnspan=2, padx=4, pady=6, sticky="NEWS")
        cloud_entry_field.pack()
        self.entries.append(network['variable'],network['cloudvariable']) 

    def networks(self):
        with open("/home/dante/networks.yml", "w") as f:
             f.write("--- #" + "\n")
             f.write("networks:" + "\n")
             for ent, cloudent in self.entries:
                    network_value=ent.get()
                    cloud_value=cloudent.get()
                    if value:
                       f.write("- { cloud: "+cloud_value+", network: "+network_value+ " }"+ "\n")
 
class ScriptPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        page_2_label = tk.Label(self, text="This is page two")
        start_button = tk.Button(self, text="Return to start page",command=lambda: master.switch_frame(StartPage))
        page_2_label.pack(side="top", fill="x", pady=10)
        start_button.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()


With this code, I have the following error:

Traceback (most recent call last):
  File "/usr/lib64/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "nwsdreamcode.py", line 53, in add_network
    self.master.switch_frame(Networks)
  File "nwsdreamcode.py", line 11, in switch_frame
    new_frame = frame_class(self)
  File "nwsdreamcode.py", line 33, in __init__
    self.create_widgets()
  File "nwsdreamcode.py", line 47, in create_widgets
    for index, cloud, network in enumerate(self.master.networks):
ValueError: need more than 2 values to unpack


How can I correct this?

Many thanks,
Albert
Was This Post Helpful? 0
  • +
  • -

#13 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 463
  • View blog
  • Posts: 1,468
  • Joined: 27-December 13

Re: Variable not sharing same value between two different functions Python

Posted 02 September 2018 - 11:32 AM

Uh, this is not a small change; it will affect many parts of your program.

In line 51-52 you make two separate append()s. This will lead to a structure that cannot be unpacked (correctly) using enumerate.
Rather you should do only one append() including both values, something like:
d = {'variable': tk.StringVar(self.master), 'cloudvariable': tk.StringVar(self.master)}
self.master.networks.append(d)
Then change line 47, 48, 55 back to the original.

Line 62 has a flaw, missing a set of parhantesis.

Line 71: What is 'value'..?

I am not sure this will do the trick, there may be need for further modifications.
Was This Post Helpful? 0
  • +
  • -

#14 albert9120   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 31-August 18

Re: Variable not sharing same value between two different functions Python

Posted 11 September 2018 - 01:07 PM

@DK3250: Thanks a lot for indications. I am very close now. The script is working and is doing what it is needed. The only thing that I do not like is that I do not have a nice page arrangement. For example, when I am clicking on "Add network", I would like to have on the left side "Tenant name" and its entry field and on the right side, but quite nearby, I would like to have the "Network name" and its entry field. When I am clicking again to add another network by pushing "Add network", I would like to get the next "Tenant name" and its own entry field + "Network name" and its own entry field right under the previous one.
Something like this:

Tenant name [entry field] Network name [entry field]
Tenant name [entry field] Network name [entry field]

Here is what I have currently:

import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.networks = []
        self.switch_frame(StartPage)
    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        start_label = tk.Label(self, text="This is the start page")
        network_button = tk.Button(self, text="Create the networks", command=lambda: master.switch_frame(Networks))
        start_label.pack(side="top", fill="x", pady=10)
        network_button.pack()

class Networks(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.entries=[]
        self.create_widgets(master)
    def create_widgets(self, master):
        label = tk.Label(self, text="Insert the name of the networks")
        start_button = tk.Button(self, text="Return to start page", command=lambda: master.switch_frame(StartPage))
        new_network_button = tk.Button(self, text="Add network", command=self.add_network)
        new_network_button.bind("<Return>", self.add_network)
        new_network_button.grid(row=len(self.master.networks), column=3, padx=4, pady=6, sticky="W")
        next_button=tk.Button(self, text="Submit", command=self.networks)    
        next_button.grid(row=1500, column=5,padx=4, pady=6, sticky="W")
        label.pack(side="top", fill="x", pady=10)
        start_button.pack()
        new_network_button.pack()
        next_button.pack()
        for index, network in enumerate(self.master.networks):
            self.render_network_field(network, index)

    def add_network(self):
        requirements={'variable': tk.StringVar(self.master), 'cloudvariable': tk.StringVar(self.master)}
        if requirements: 
           self.master.networks.append(requirements)
           self.master.switch_frame(Networks)
        else: 
           tkMessageBox.showerror("tk", "No networks defined!")
           self.master.switch_frame(Networks)

    def render_network_field(self, network, index):
        labelText=tk.StringVar()
        labelText.set("Tenant name")
        labelDir=tk.Label(self,textvariable=labelText, height=4)
        labelDir.pack(side="top")
        nw_entry_field = tk.Entry(self, textvariable=network['variable'])
        nw_entry_field.grid(row=index, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
        nw_entry_field.pack(side="right")
        labelText=tk.StringVar()
        labelText.set("Network name")
        labelDir=tk.Label(self,textvariable=labelText, height=4)
        labelDir.pack(side="top")
        cloud_entry_field = tk.Entry(self, textvariable=network['cloudvariable'])
        cloud_entry_field.grid(row=index, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
        cloud_entry_field.pack(side="right")
        self.entries.append((network['cloudvariable'],network['variable']))

    def networks(self):
        with open("/home/dante/networks.yml", "w") as f:
             f.write("--- #" + "\n")
             f.write("networks:" + "\n")
             for ent, cloudent in self.entries:
                    network_value=ent.get()
                    cloud_value=cloudent.get()
                    if network_value:
                      if cloud_value:
                        f.write("- { cloud: "+cloud_value+", network: "+network_value+ " }"+ "\n")

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()


How can I arrange everything in page accordingly?

Many thanks,
Albert
Was This Post Helpful? 0
  • +
  • -

#15 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 463
  • View blog
  • Posts: 1,468
  • Joined: 27-December 13

Re: Variable not sharing same value between two different functions Python

Posted 11 September 2018 - 01:19 PM

Try the grid geometry manager: http://effbot.org/tkinterbook/grid.htm
This will not work with pack - you need to those between the two.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2