How to access a variable from one tab in another tab of a notebook?

Alan Gauld alan.gauld at yahoo.co.uk
Wed Apr 7 19:49:37 EDT 2021


On 07/04/2021 09:35, Mohsen Owzar wrote:

> The problem is that I can't use the variable "val" from Tab2 in Tab 1, 

> # Filename: Tab1.py
> from tkinter import *
> 
> def gen_t1(frame):
>   f = LabelFrame(frame, text='f', bg='lightgreen')
>   f.pack(expand=True, fill='both')
> 
>   b1 = Button(f, text='B1').pack()
> 
> ##  if val > 5:


> # Filename: Tab2.py
> from tkinter import *
> 
> def gen_t2(frame):
>   def getValue(event):
>     val = ent.get()
>     print(val)

Note that val is a local variable within a nested function.
It only exists while the nested function is executing.
As soon as the function ends val is thrown away.

If you want the value of the entry you need to store it
in a variable that is visible after the function exits
(by returning it perhaps? or setting a global - ugly)

But you still have the problem of making that visible
to Tab1. You could import tab2 into tab1 and use Tab2.varName

But this is why GUIs are often(usually?) built as a class
because you can store all the state variables within
the instance and access them from all the methods.

You can do it with functions but you usually wind up
with way too many globals to be comfortable.

> from Tab1 import gen_t1
> from Tab2 import gen_t2
...
> def on_tab_change(event):
>   global firstTime1, firstTime2
>   
>   tab = event.widget.tab('current','text')
>   if tab == 'Tab 1':
>     print('Tab 1')
>     if firstTime1 == 1:
>       gen_t1(tab1)
>       firstTime1 = 0

Probably nicer to use boolean values for
firstTime1 and firstTime2, ie True and False
rather than their numeric equivalents.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Python-list mailing list