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

Mohsen Owzar mohsen.owzar at gmail.com
Wed Apr 7 04:35:31 EDT 2021


Hi guys
I have written a GUI with two tabs, Tab 1 and Tab 2 as shown below:
On Tab 2 should be my settings parameters placed like "Val".
If the user types a value greater than 5 in the entry field, the background color of Tab1 should be changed from light green to gray and the button "B1" should be disabled
The problem is that I can't use the variable "val" from Tab2 in Tab 1, even if I have defined in every function and file as the global. It brought all the times the error message "val is not defined in Tab 1".
You can run the top level "TabTop" to see my GUIs and uncomment the if part in Tab1 to see the error message.
Any help is really appreciated 
Regards
Mohsen

 
# 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:
##    f_enabled = 'disabled'
##    f['bg'] = 'lightgray'
##  else:
##    f_enabled = 'normal'
##    f['bg'] = 'lightgreen'	 
######################################
# Filename: Tab2.py
from tkinter import *

def gen_t2(frame):
  def getValue(event):
    val = ent.get()
    print(val)

  lbl = Label(frame, text='Val').pack()

  ent = Entry(frame)
  ent.pack()
  ent.insert(0, '2')
  
  ent.bind('<Return>', getValue)

The code for the top level is:
######################################
# Filename: TabTop
from tkinter import *
from tkinter import ttk

from Tab1 import gen_t1
from Tab2 import gen_t2

global nb

firstTime1 = 1
firstTime2 = 1

root = Tk()
root.title('Tab-Tester')
root.geometry('300x200')

nb = ttk.Notebook(root)
tab1 = Frame(nb)
tab2 = Frame(nb)
  
nb.add(tab1, text ='Tab 1')
nb.add(tab2, text ='Tab 2')
nb.pack(expand = 1, fill ="both")

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
      
  elif tab == 'Tab 2':
    print('Tab 2')
    if firstTime2 == 1:
      gen_t2(tab2)
      firstTime2 = 0

nb.bind('<<NotebookTabChanged>>', on_tab_change)

root.mainloop()



More information about the Python-list mailing list