python object is NoneType even after declaring as global: ttk textbox

2020-06-15 Thread emagnun
I have a very simple script that retrieves the value from a text box upon click 
of a checkButton. But in click event, I'm receiving text box object as NoneType 
even after setting it as global. Pls help.

Output: !!ERROR!! Tag is None

### Source Code ###
from tkinter import *
from tkinter import ttk
import os

def submitData():
global tag
global tagBox
if (tagBox is not None):
tag = tagBox.get("1.0","end-1c")
print ("!!SUCESS!! tag -->", tag)
else:
print ("!!ERROR!! Tag is None")

gui = Tk()
gui.title("GUI")
gui.geometry('250x300')

tag = "NA"
tagBoxLabel = Label(gui, text = "Tag: ").grid(column=0, row=5, pady=30, 
sticky="EN")
tagBox = Text(gui, height=1, width=20).grid(column=1, row=5, pady=30, 
sticky="WN")

submitButton = ttk.Button(gui, text="Submit", command=lambda: 
submitData()).grid(column=1, row=7)
gui.mainloop()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python object is NoneType even after declaring as global: ttk textbox

2020-06-15 Thread Peter Otten
emagnun wrote:

> I have a very simple script that retrieves the value from a text box upon
> click of a checkButton. But in click event, I'm receiving text box object
> as NoneType even after setting it as global. Pls help.
> 
> Output: !!ERROR!! Tag is None
> 
> ### Source Code ###
> from tkinter import *
> from tkinter import ttk
> import os
> 
> def submitData():
> global tag
> global tagBox

You do not need the global declaration for tagBox as you do not rebind that 
name.

> if (tagBox is not None):
> tag = tagBox.get("1.0","end-1c")
> print ("!!SUCESS!! tag -->", tag)
> else:
> print ("!!ERROR!! Tag is None")
> 
> gui = Tk()
> gui.title("GUI")
> gui.geometry('250x300')
> 
> tag = "NA"
> tagBoxLabel = Label(gui, text = "Tag: ").grid(column=0, row=5, pady=30,
> sticky="EN") 
> tagBox = Text(gui, height=1, width=20).grid(column=1, row=5,
> pady=30, sticky="WN")

The grid() method always returns None. So tagBoxLabel, tagBox, and 
submitButton are all bound to None.

To get a reference of the widget you need two steps:

# bind tagBox
tagBox = Text(...)

# define layout
tagBox.grid(...)
 
> submitButton = ttk.Button(gui, text="Submit", command=lambda:
> submitData()).grid(column=1, row=7)
> gui.mainloop()

Superfluous lambda alert: instead of 

lambda: submitData()

just write

submitData

, i. e.:

ttk.Button(..., command=submitData).grid()


-- 
https://mail.python.org/mailman/listinfo/python-list